Java's request Case - User Login

Case user login requirements:

1. Preparation login.html two login page username & password input box 
2. Druid database connection pooling, MySQL operation, DB1 database user table 
3. JdbcTemplate art package the JDBC 
4. Jump to a successful login SuccessServlet show: Log success! User name, you are welcome 
5. Jump to FailServlet show login failure: Login failed for user name or password is incorrect

  

Analysis diagram:

Development steps:

1, create a JavaEE project, create login.html page, create durid.properties configuration file, import jar package

2, create a database environment

1 CREATE DATABASE db1;
2 USE db1;
3 CREATE TABLE USER(
4         
5   id INT PRIMARY KEY AUTO_INCREMENT,
6   username VARCHAR(32) UNIQUE NOT NULL,
7   PASSWORD VARCHAR(32) NOT NULL
8);

 

3, create a JavaBean, User class

 1 /*
 2 javaBean 类
 3  */
 4 public class User {
 5 
 6     private int id;
 7     private String username;
 8     private String password;
 9 
10     public User() {
11     }
12 
13     public User(int id, String username, String password) {
14         this.id = id;
15         this.username = username;
16         this.password = password;
17     }
18 
19     @Override
20     public String toString() {
21         return "User{" +
22                 "id=" + id +
23                 ", username='" + username + '\'' +
24                 ", password='" + password + '\'' +
25                 '}';
26     }
27 
28     public int getId() {
29         return id;
30     }
31 
32     public void setId(int id) {
33         this.id = id;
34     }
35 
36     public String getUsername() {
37         return username;
38     }
39 
40     public void setUsername(String username) {
41         this.username = username;
42     }
43 
44     public String getPassword() {
45         return password;
46     }
47 
48     public void setPassword(String password) {
49         this.password = password;
50     }
51 }
View Code

 

4, create a database connection pooling tools JDBCUtils

 1 import com.alibaba.druid.pool.DruidDataSourceFactory;
 2 
 3 import javax.sql.DataSource;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.sql.Connection;
 7 import java.sql.SQLException;
 8 import java.util.Properties;
 9 
10 public class JDBCUtils {
11 
12     private static DataSource ds;
13 
14     static {
15         try {
16             // load configuration file 
. 17              the Properties prop = new new the Properties ();
 18 is  
. 19              // Use the configuration file is loaded into memory classloader 
20 is              the InputStream IS = JDBCUtils. Class .getClassLoader () the getResourceAsStream ( "druid.properties." );
 21 is  
22 is              prop. Load (IS);
 23 is  
24              // initialize the connection pool object 
25              DS = DruidDataSourceFactory.createDataSource (prop);
 26 is          } the catch (IOException E) {
 27              e.printStackTrace ();
 28          } the catch(Exception E) {
 29              e.printStackTrace ();
 30          }
 31 is      }
 32  
33 is      / * 
34 is          to obtain a connection pool object
 35       * / 
36      public  static the DataSource getDataSource () {
 37 [          return DS;
 38 is      }
 39  
40      / * 
41 is          acquired connection connector Object
 42 is       * / 
43 is      public  static Connection the getConnection () throws SQLException {
 44 is          return ds.getConnection ();
 45      }
 46 is }
View Code

 

5, create UserDao class that provides login methods

. 1  Import org.springframework.dao.DataAccessException;
 2  Import org.springframework.jdbc.core.BeanPropertyRowMapper;
 . 3  Import org.springframework.jdbc.core.JdbcTemplate;
 . 4  
. 5  public  class UserDao {
 . 6      // declare JDBCTemplate object shared 
. 7      Private the JdbcTemplate = Template new new the JdbcTemplate (JDBCUtils.getDataSource ());
 . 8  
. 9      / ** 
10       * log method
 . 11       * @param loginUser only the user name and password
 12 is       * @return all user data does not contain the user's query to return null
13      */
14    public User login(User loginUser) {
15 
16        try {
17            // 编写 SQL
18            String sql = "select * from user where username = ? and password = ?";
19 
20            // 调用query 方法
21            User user = template.queryForObject(sql,
22                     new BeanPropertyRowMapper<User>(User.class),
23                    loginUser.getUsername(),loginUser.getPassword());
24 
25            return user;
26        } catch (DataAccessException e) {
27            e.printStackTrace();
28            return null;
29        }
30 
31 
32 
33    }
34 }
View Code

 

6. Test the login method

 1 import org.junit.Test;
 2 
 3 public class LoginTest {
 4 
 5     @Test
 6     public void test() {
 7         User loginuser = new User();
 8         loginuser.setUsername("admin");
 9         loginuser.setPassword("admin");
10         UserDao dao = new UserDao();
11 
12         User user = dao.login(loginuser);
13         System.out.println(user);
14 
15     }
16 }
View Code

 

7, write loginServlet class

 1 import org.apache.commons.beanutils.BeanUtils;
 2 
 3 import javax.servlet.ServletException;
 4 import javax.servlet.annotation.WebServlet;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 import java.io.IOException;
 9 import java.lang.reflect.InvocationTargetException;
10 import java.util.Map;
11 
12 @WebServlet("/loginservlet")
13 public class LoginServlet extends HttpServlet {
14     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
15         // 1.设置编码
16         request.setCharacterEncoding("utf-8");
17 
18        // 2 获取请求参数
19          String username = request.getParameter("username");
20         String password = request.getParameter("password");
21 
22         // 3 封装 user 对象
23        User loginUser = new User();
24 
25         loginUser.setUsername(username);
26         loginUser.setPassword(password);
27 
28        
29         // 4.调用 userdao 的 login方法
30         UserDao dao = new UserDao();
31         User user = dao.login(loginUser);
32 
33         //5. 判断
34         if(user == null) {
35             request.getRequestDispatcher("/failServlet").forward(request,response);
36         } else {
37             request.setAttribute("user",user);
38             request.getRequestDispatcher("/successServlet").forward(request,response);
39         }
40     }
41 
42     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
43         this.doPost(request,response);
44     }
45 }
View Code

 

8, write FailServlet class and class SuccessServlet

  FailServlet class

 1 import javax.servlet.ServletException;
 2 import javax.servlet.annotation.WebServlet;
 3 import javax.servlet.http.HttpServlet;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 import java.io.IOException;
 7 
 8 @WebServlet("/failServlet")
 9 public class FailServlet extends HttpServlet {
10     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
11         response.setContentType("text/html;charset=utf-8");
12 
13         response.getWriter().write("登录失败");
14     }
15 
16     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17 
18     }
19 }
View Code

 

  SuccessServlet class

 1 import javax.servlet.ServletException;
 2 import javax.servlet.annotation.WebServlet;
 3 import javax.servlet.http.HttpServlet;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 import java.io.IOException;
 7 
 8 @WebServlet("/successServlet")
 9 public class SuccessServlet extends HttpServlet {
10     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
11         User user = (User) request.getAttribute("user");
12 
13         if(user!=null) {
14             // 设置编码
15             request.setCharacterEncoding("utf-8");
16             response.setContentType("text/html;charset=utf-8");
17 
18             response.getWriter().write("登录成功"+user.getUsername()+"欢迎您");
19         }
20     }
21 
22     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
23 
24     }
25 }
View Code

 

9, action path in form form login.html wording

action = "+ Servlet virtual directory resource path"

  

Guess you like

Origin www.cnblogs.com/niujifei/p/11620609.html