Learning Notes - User Login Case

Demand:

  1. Write login.html login page
  2. Using Druid database connection pool technology to manipulate user tables in mysql database
  3. Encapsulation of JDBC using JdbcTemplate Technology
  4. Log in successfully jumped to Success Servlet display: Log in successfully! User name, welcome to you
  5. Logon Failure Jump to FailServlet Show: Logon Failure, User Name or Password Error

Steps:

  1. Write html pages, configuration files, and import jar packages
    Relevant jar packages (jar packages placed under web/WEB-INF/lib):

    			commons-beanutils-1.8.0.jar//BeanUtils jar package
    			commons-logging-1.2.jar
    			druid-1.0.9.jar //druid connection pool jar package
    			mysql-connector-java-5.1.37-bin.jar //Database-driven jar package
    			mchange-commons-java-0.2.12.jar //The following are JdbcTemplate related jar packages
    			spring-beans-5.0.0.RELEASE.jar
    			spring-core-5.0.0.RELEASE.jar
    			spring-jdbc-5.0.0.RELEASE.jar
    			spring-tx-5.0.0.RELEASE.jar
    

html page (in web directory): login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--action The value is virtual directory+Resource Path-->
    <form action="/test/loginServlet" method="post">
        User name:<input type="text" name="username"> <br>
        Password:<input type="password" name="password"><br>

        <input type="submit" value="Sign in">

    </form>
</body>
</html>

Configuration file (under src): druid.properties

#Registration Driver
driverClassName=com.mysql.jdbc.Driver
#url of database connection
url=jdbc:mysql:///mydbone
#User name and password
username=root
password=root
#Connection pool initialization size
initialSize=5
#Maximum Connection Pool Activity
maxActive=10
#Max Delay
maxWait=3000
  1. Create User classes under the domain package

    package com.fengqi.domain;
    
    /**
     * @Author: NieFengQi
     * @Date: 2019/7/27 16:46
     * @Decription:User's Entity Class
     */
    
      
    
          public class User {
                private int id;
                private String username;
                private String password;
        
            public User() {
            }
        
            public User(String username, String password) {
        
                this.username = username;
                this.password = password;
            }
        
            public User(int id, String username, String password) {
                this.id = id;
                this.username = username;
                this.password = password;
            }
        
            public int getId() {
                return id;
            }
        
            public void setId(int id) {
                this.id = id;
            }
        
            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;
            }
        
            @Override
            public String toString() {
                return "User{" +
                        "id=" + id +
                        ", username='" + username + '\'' +
                        ", password='" + password + '\'' +
                        '}';
            }
           }
    
  2. Writing tool class JDBCUtils under utils package

    	package com.fengqi.util;
    	
    	import com.alibaba.druid.pool.DruidDataSourceFactory;
    	
    	import javax.sql.DataSource;
    	import java.io.IOException;
    	import java.io.InputStream;
    	import java.sql.Connection;
    	import java.sql.SQLException;
    	import java.util.Properties;
    	
    	/**
    	 * @Author: NieFengQi
    	 * @Date: 2019/7/27 16:55
    	 * @Decription:JDBC Tool class use, using Druid connection pool technology
    	 */
    	
    	  
    	
    	      public class JDBCUtils {
    	
    	        private static DataSource ds;
    	    
    	        static {
    	            try {
    	                //Loading configuration files
    	                Properties pro = new Properties();
    	                InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
    	                pro.load(is);
    	                //Initialize connection pool objects through Druid connection pool factory objects
    	                ds = DruidDataSourceFactory.createDataSource(pro);
    	            } catch (IOException e) {
    	                e.printStackTrace();
    	            } catch (Exception e) {
    	                e.printStackTrace();
    	            }
    	        }
    	    
    	        /**
    	         * Get the connection pool object
    	         */
    	        public static DataSource getDataSource(){
    	            return ds;
    	        }
    	    
    	    
    	        /**
    	         * Get the Connection object
    	         */
    	        public static Connection getConnection() throws SQLException {
    	            return ds.getConnection();
    	        }
    	    }
    
  3. Create UserDao in the dao package to provide login methods

    package com.fengqi.dao;
    
    import com.fengqi.domain.User;
    import com.fengqi.util.JDBCUtils;
    import org.springframework.dao.DataAccessException;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    /**
     * @Author: NieFengQi
     * @Date: 2019/7/27 16:50
     * @Decription:Classes that operate on user tables in a database
     */
    
        public class UserDao {
        
            //Declare JdbcTemplate to share this object
            private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
        
            /**
             *
             * @param loginUser Only username and password
             * @return user Contains all fields of the User class and returns null if not queried
             */
            public User login(User loginUser){
                try {
                    //Writing SQL
                    String sql = "select * from user where username=? and password=?";
                    //Query sql through the method in template and encapsulate it as a corresponding object
                    User user = template.queryForObject(sql,
                            new BeanPropertyRowMapper<User>(User.class),
                            loginUser.getUsername(),loginUser.getPassword());
                    return user;
                } catch (DataAccessException e) {
                    e.printStackTrace();
                    //If an exception occurs, it returns empty (no query is found)
                    return null;
                }
        
            }
        }
    
  4. Write LoginServlet, FailServlet, Success Servlet under the servlet package
    LoginServlet:

    	package com.fengqi.web.servlet;
    	
    	import com.fengqi.dao.UserDao;
    	import com.fengqi.domain.User;
    	import org.apache.commons.beanutils.BeanUtils;
    	
    	import javax.servlet.ServletException;
    	import javax.servlet.annotation.WebServlet;
    	import javax.servlet.http.HttpServlet;
    	import javax.servlet.http.HttpServletRequest;
    	import javax.servlet.http.HttpServletResponse;
    	import java.io.IOException;
    	import java.lang.reflect.InvocationTargetException;
    	import java.util.Map;
    	
    	/**
    	 * @Author: NieFengQi
    	 * @Date: 2019/7/28 10:27
    	 * @Decription:
    	 */
    	@WebServlet("/loginServlet")
    	public class LoginServlet extends HttpServlet {
    	    @Override
    	    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	        //Setting Code
    	        req.setCharacterEncoding("utf-8");
    	
    	        /*//Get the request parameters
    	        String username = req.getParameter("username");
    	        String password = req.getParameter("password");
    	        //Encapsulate the request parameters as User objects and call the login method of UserDao
    	        User user = new UserDao().login(new User(username, password));*/
    	
    	        //Get all request parameters
    	        Map<String, String[]> parameterMap = req.getParameterMap();
    	        //Create empty User objects
    	        User loginUser = new User();
    	        //Encapsulating User Objects with BeanUtils
    	        try {
    	            BeanUtils.populate(loginUser,parameterMap);
    	        } catch (IllegalAccessException e) {
    	            e.printStackTrace();
    	        } catch (InvocationTargetException e) {
    	            e.printStackTrace();
    	        }
    	        //Call the login method in UserDao and return to user
    	        User user = new UserDao().login(loginUser);
    	
    	        //Determine whether the returned user is empty
    	        if (user != null){
    	            //Set shared properties if not null and forward them to Success Servlet
    	            req.setAttribute("user",user);
    	            req.getRequestDispatcher("/successServlet").forward(req,resp);
    	        }else {
    	            //If null, forward to FailServlet
    	            req.getRequestDispatcher("/failServlet").forward(req,resp);
    	        }
    	    }
    	
    	    @Override
    	    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	        this.doPost(req,resp);
    	    }
    	}
    

FailServlet:

	    package com.fengqi.web.servlet;
	    
	    import javax.servlet.ServletException;
	    import javax.servlet.annotation.WebServlet;
	    import javax.servlet.http.HttpServlet;
	    import javax.servlet.http.HttpServletRequest;
	    import javax.servlet.http.HttpServletResponse;
	    import java.io.IOException;
	    
	    /**
	     * @Author: NieFengQi
	     * @Date: 2019/7/28 10:47
	     * @Decription:
	     */
	    @WebServlet("/failServlet")
	    public class FailServlet extends HttpServlet {
	        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	            //Set up the corresponding encoding
	            response.setContentType("text/html;charset=utf-8");
	            //Response to login failure to page
	            response.getWriter().write("<h1 align='center'>Landing Failure,Error in username or password!!!</h1>");
	        }
	    
	        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	            this.doPost(request,response);
	        }
	    }

SuccessServlet:

	    package com.fengqi.web.servlet;
	    
	    import com.fengqi.domain.User;
	    
	    import javax.servlet.ServletException;
	    import javax.servlet.annotation.WebServlet;
	    import javax.servlet.http.HttpServlet;
	    import javax.servlet.http.HttpServletRequest;
	    import javax.servlet.http.HttpServletResponse;
	    import java.io.IOException;
	    
	    /**
	     * @Author: NieFengQi
	     * @Date: 2019/7/28 10:43
	     * @Decription:
	     */
	    @WebServlet("/successServlet")
	    public class SuccessServlet extends HttpServlet {
	        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	            //Setting Response Coding
	            response.setContentType("text/html;charset=utf-8");
	            //Getting attributes from the request domain
	            User user = ((User) request.getAttribute("user"));
	            //Response to successful landing to the page
	            response.getWriter().write("<h1 align='center'>The landing was successful."+user.getUsername()+"Welcome!!!</h1>");
	        }
	    
	        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	            this.doPost(request,response);
	        }
	    }

Expand:

BeanUtils Tool Class to Simplify Data Encapsulation
		* Used to encapsulate JavaBean s
		1. JavaBean: Standard Java classes
			1. Requirements:
				1. Classes must be modified by public
				2. Constructors that must provide empty parameters
				3. Membership variables must be private ly modified
				4. Provide common setter and getter methods
			2. Function: encapsulating data


		2. Concept:
			Membership variables:
			Attribute: The product of interception of setter and getter methods
				For example: getUsername () --> Username --> username


		3. Methods:
			1. setProperty()
			2. getProperty()
			3. populate (Object obj, Map map): Encapsulate the key-value pair information of the map set into the corresponding JavaBean object

Tags: Java Druid JDBC SQL

Posted on Wed, 31 Jul 2019 01:43:03 -0700 by big_al