使用Servlet和jdbc建立用戶登陸驗證

首先建立一個用戶表,用來保存用戶名 密碼,並插入幾條數據java

mysql> desc user;
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(20) | YES | | NULL | |
| password | varchar(50) | YES | | NULL | |
+----------+-------------+------+-----+---------+----------------+mysql

建立語句,注意必定要設置password的長度超過41,由於插入數據時咱們使用password函數,生成長度爲41的字符串,web

例如:sql

mysql> select password('aasas');
+-------------------------------------------+
| password('aasas') |
+-------------------------------------------+
| *462034BF6D04324F93F1F6CA352B23079A165972 |
+-------------------------------------------+
1 row in set (0.00 sec)數據庫

mysql> select length( password('aasas'));
+----------------------------+
| length( password('aasas')) |
+----------------------------+
| 41 |
+----------------------------+
1 row in set (1.76 sec)session

 

 CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,          
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 

插入數據:app

       mysql> insert into user(username,password) values('root',password('root'));jsp

查看一下插入結果:此時密碼已經變成一串字符串.函數

   

mysql> select * from user where username='root';
+----+----------+-------------------------------------------+
| id | username | password |
+----+----------+-------------------------------------------+
| 4 | root | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
+----+----------+-------------------------------------------+
1 row in set (0.00 sec)post

      2.建立一個java web project,新建一個名爲user的類,使用jdbc連接數據庫,把user表的數據拿出來和輸入的用戶名密碼對比,並添加validate方法

若是用戶名密碼正確,返回true。以後注意將Mysql JDBC的driver copy到lib目錄下,不然沒法運行

 

package com.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class user {

    private static String userName;
    private static String password;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public static boolean validate()
    {
        String url = "jdbc:mysql://localhost:3306/study";
        String user= "root";
        String dbpassword = "3edc4rfv";
        boolean result = false;
        
        try {
             String driver ="com.mysql.jdbc.Driver";
             Class.forName(driver);
             Connection   con = DriverManager.getConnection(url,user, dbpassword);
             
            if(con==null){
                System.out.println("can't open DBConnection");
            }
            
            String sql = "select * from user where username=? and password=password(?)";
            
            PreparedStatement pstmt=con.prepareStatement(sql); 
            pstmt.setString(1, userName);
            pstmt.setString(2, password);
            System.out.println(sql);
            ResultSet rs=pstmt.executeQuery();
            if(rs.next())
            {
                System.out.println("PASS");
                result=true;
                
            }
            else
            {
                System.out.println("FAIl");
                result=false;
            }
            pstmt.close();
            rs.close();
            con.close();
    
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
        
    }
    
}

 

並新建一個Servlet,包名com.web,class name login.java,這裏主要使用post方法,因此在dopost方法添加代碼

 將login.java 修改成這樣:

package com.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.data.book;
import com.data.user;

public class login extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public login() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

         //Add some codes
        doPost(request,response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         request.getParameter("username");
         request.getParameter("password");
         request.getSession().setAttribute("user", request.getParameter("username"));      //將user放在Attribute中
         user user1=new user();
         user1.setUserName(request.getParameter("username"));
         user1.setPassword(request.getParameter("password"));
         System.out.println(request.getParameter("username")+request.getParameter("password"));
         
         if(user1.validate())
         {
           
             request.getRequestDispatcher("welcome.jsp").forward(request, response); //校驗用戶名密碼正確,跳轉到welcome.jsp
              
         }
         else
         {
             request.getRequestDispatcher("index.jsp").forward(request, response);  //校驗用戶名密碼不正確,跳轉到index.jsp
             
         }
         
    }
    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

 

      此時web.xml代碼以下。能夠使用login.do訪問這個Servlet

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>login Page</description>
    <display-name>login Page</display-name>
    <servlet-name>login</servlet-name>
    <servlet-class>com.web.login</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3.在jsp頁面添加相應的action,在index.jsp的body標籤之間添加,會生出登陸界面,用戶名 密碼

 <form action="login.do" method="post" > 
   username<input type="text" name="username">
   <br>password
   <input type="password" name="password">
   <br>
   <input type="submit"  value="login">
   <input type="reset" value="cancel"/>
   </form>

4.添加welcome.jsp

在welcome.jsp body標籤添加 

  Welcome <%=session.getAttribute("user") %><br>

 

5.加載工程

相關文章
相關標籤/搜索