Use java, tomcat, mysql to achieve login function

The first step is to create a dynamic web project
New-Other Find the Dynamic Web Project under the web and click Next

to enter the project name and complete.
write picture description here

The second step is to import the JDBC package and configure the Tomcat service.
For importing the jar package, please refer to the common method in the link below. I will not introduce more here
http://blog.csdn.net/children_of_light/article/details/54985869
write picture description here

Configure the Tomcat service as shown in the figure, find Window-Preferences-Server-Runtime Environm and click Add...then OK
write picture description here

At this time, select the required Tomcat version according to your needs. Here is an example of selecting Tomcat v8.0. You can select the Tomcat path next, or if you are an old driver who has already set the path, you can directly Finish
write picture description here

Next, right-click your project, click Build Path-Configure Build Path... Find the jva Build Path in the new window and click Add Library... then OK
write picture description here

In the new window select Server Runtime and then Next
write picture description here

Finally, select the Tomcat you just selected and press Finish, so that the service is started.
write picture description here

The third step key code

The following is the form code of the login interface JSP. There are some points to pay attention to. Remember to add type="submit",

<form class="login" action="loginservlet" method="post">
            <p class="title">Log in</p>
            <input type="text" placeholder="Username" autofocus name="username" />
            <i class="fa fa-user"></i> 
            <input type="password" placeholder="Password" name="password" /> <i class="fa fa-key"></i>
            <a href="#">Forgot your password?</a>
            <button type="submit">
                <i class="spinner"></i> <span class="state">Log in</span>
            </button>
        </form>

Next, we need to create a container servlet. Here, right-click the project, New, and Servlet enter the package name and class
write picture description here
name in the blank of the new window (the package to be created and the class to be created). In the class just created, let's modify the code, This class can get the code under the front-end form
write picture description here

The class has two methods by default, doPost(), and doGet()
because our front-end code used method="post",
so we just need to change doPost()

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class loginservlet
 */
@WebServlet("/loginservlet")
public class loginservlet extends HttpServlet {
    
    
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public loginservlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * request请求
     * response响应
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("数据穿到这里");


        String username = request.getParameter("username");//获取表单中name="username"
        String userpassword = request.getParameter("password");//获取表单中nam="password"的数据

        System.out.println(username + "," + userpassword);//测试是否能够传到这里

        //接下来是验证表单数据是否与数据库数据相匹配
        sqlD util = new sqlD(); //jdbc连接数据库的类
        if (util.login(username, userpassword) == 1) { //在sqlD类中的login方法,如果返回值为1,if语句为true
            System.out.println("登录成功!");
            response.sendRedirect("suce.jsp");          //跳转到登录成功的页面

            /*第二种跳转方式,并且能够传参
             * request.setAttribute("username", username);  
             * request.getRequestDispatcher("suce.jsp").forward(request, response);
             */
        }else {                                     //如果if语句为false,跳转会登录界面或者跳转到失败界面
            System.out.println("登录失败!");
            response.sendRedirect("NewFile.jsp");
        }
    }
}

The following is the class that connects to the database. There is also a method
in the class to compare whether the parameters passed from the doPost() method are equal to the database data.


/**
 * 数据库工具类 
 * @author Administrator
 *
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class sqlD {
    
     
    public static Connection getConnection(){ //连接数据库的方法
        //与特定数据库的连接(会话)。在连接上下文中执行 SQL 语句并返回结果。 
        Connection conn=null;
                             //连接的IP加端口号    //数据库名     //跳过安全认证
        String ip="jdbc:mysql://localhost:3306/oli?useSSL=false";
        String username="root";     //数据库用户名
        String password="123456";//数据库用户密码
        try {   //返回与带有给定字符串名的类或接口相关联的 Class 对象。    
            Class.forName("com.mysql.jdbc.Driver");//指向jdbc包下的"com.mysql.jdbc.Driver"类
//管理一组 JDBC 驱动程序的基本服务。      //试图建立到给定数据库 URL 的连接。
            conn=DriverManager.getConnection(ip,username,password);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
public int login(String username,String userpassword){ //将doPost()传来的值和数据库用户密码表的数据相比较

        Connection conn = getConnection();//与特定数据库的连接(会话)。在连接上下文中执行 SQL 语句并返回结果。 

        if (conn != null) {
            Statement stat = null;

            ResultSet rs = null;//表示数据库结果集的数据表,

            try {
                stat = conn.createStatement(); //创建一个 Statement 对象来将 SQL 语句发送到数据库。
                //数据库条件查询语句
                String sql = "select * from user where username='"+username+"' and userpassword='"+userpassword+"'";
                rs = stat.executeQuery(sql);//executeQuery()执行给定的 SQL 语句,该语句返回单个 ResultSet 对象。
                if (rs.next()) { //有返回结果集为true,帐号密码正确
                    return 1;//方法返回1
                }else {
                    return 0;//方法返回0
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0;   //方法返回0
    }
}

Enter the account password from the form, and then pass the data to the doPost method, and compare the query method passed to the database connection method. If a result set is returned, the account password is correct. Through the return value, we can set the jump interface in the judgment statement.
Login function achieved successfully

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324157490&siteId=291194637