Java language -- user login case

Case: user login

User login case requirements:

1. Write two input boxes of login.html login page username & password
2. use the Druid database connection pool technology to operate the user table in the mysql and day14 databases
3. Using JdbcTemplate technology to encapsulate JDBC
4. Log in successfully and jump to SuccessServlet display: log in successfully! User name, welcome
5. Login failure jump to FailServlet display: login failure, wrong user name or password

Can be extracted directly first Source code

  • Analysis and development steps
    1. Create project, import html page, configuration file, jar package

    2. Create database environment

    3. Create package cn.itcast.domain, and create class User

package cn.itcast.domain;
			/**
			 * User's entity class
			 */
			public class User {
			
			    private int id;
			    private String username;
			    private String 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 + '\'' +
			                '}';
			    }
			}
  1. Create package cn.itcast.util and write tool class JDBC utils
package cn.itcast.util;

			import com.alibaba.druid.pool.DruidDataSourceFactory;
			
			import javax.sql.DataSource;
			import javax.xml.crypto.Data;
			import java.io.IOException;
			import java.io.InputStream;
			import java.sql.Connection;
			import java.sql.SQLException;
			import java.util.Properties;
			
			/**
			 * JDBC Tool class uses Durid connection pool
			 */
			public class JDBCUtils {
			
			    private static DataSource ds ;
			
			    static {
			
			        try {
			            //1. Load configuration file
			            Properties pro = new Properties();
			            //Use ClassLoader to load configuration file and get byte input stream
			            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
			            pro.load(is);
			
			            //2. Initialize connection pool object
			            ds = DruidDataSourceFactory.createDataSource(pro);
			
			        } catch (IOException e) {
			            e.printStackTrace();
			        } catch (Exception e) {
			            e.printStackTrace();
			        }
			    }
			
			    /**
			     * Get connection pool object
			     */
			    public static DataSource getDataSource(){
			        return ds;
			    }
			
			
			    /**
			     * Get Connection object
			     */
			    public static Connection getConnection() throws SQLException {
			        return  ds.getConnection();
			    }
			}
  1. Create package cn.itcast.dao, create class UserDao, and provide login method
package cn.itcast.dao;

			import cn.itcast.domain.User;
			import cn.itcast.util.JDBCUtils;
			import org.springframework.dao.DataAccessException;
			import org.springframework.jdbc.core.BeanPropertyRowMapper;
			import org.springframework.jdbc.core.JdbcTemplate;
			
			/**
			 * Class of User table in operation database
			 */
			public class UserDao {
			
			    //Declare JDBC template object sharing
			    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
			
			    /**
			     * Login method
			     * @param loginUser Only user name and password
			     * @return user Contains all user data, no query found, return null
			     */
			    public User login(User loginUser){
			        try {
			            //1. writing sql
			            String sql = "select * from user where username = ? and password = ?";
			            //2. Call query method
			            User user = template.queryForObject(sql,
			                    new BeanPropertyRowMapper<User>(User.class),
			                    loginUser.getUsername(), loginUser.getPassword());
			
			
			            return user;
			        } catch (DataAccessException e) {
			            e.printStackTrace();//Log
			            return null;
			        }
			    }
			}
  1. Write cn.itcast.web.servlet.LoginServlet class
package cn.itcast.web.servlet;

			import cn.itcast.dao.UserDao;
			import cn.itcast.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;
			
			
			@WebServlet("/loginServlet")
			public class LoginServlet extends HttpServlet {
			
			
			    @Override
			    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			        //1. Set code
			        req.setCharacterEncoding("utf-8");
			        //2. Get request parameters
			        String username = req.getParameter("username");
			        String password = req.getParameter("password");
			        //3. Encapsulate user object
			        User loginUser = new User();
			        loginUser.setUsername(username);
			        loginUser.setPassword(password);
			
			        //4. Call the login method of UserDao
			        UserDao dao = new UserDao();
			        User user = dao.login(loginUser);
			
			        //5. judge user
			        if(user == null){
			            //Login failed
			            req.getRequestDispatcher("/failServlet").forward(req,resp);
			        }else{
			            //Login successfully
			            //Store data
			            req.setAttribute("user",user);
			            //Forward
			            req.getRequestDispatcher("/successServlet").forward(req,resp);
			        }
			
			    }
			
			    @Override
			    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			        this.doGet(req,resp);
			    }

			}
  1. Write FailServlet and SuccessServlet classes
@WebServlet("/successServlet")
			public class SuccessServlet extends HttpServlet {
			    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			        //Get the user object shared in the request domain
			        User user = (User) request.getAttribute("user");
			
			        if(user != null){
			            //Write a sentence to the page
			
			            //Set encoding
			            response.setContentType("text/html;charset=utf-8");
			            //output
			            response.getWriter().write("Login succeeded!"+user.getUsername()+",Welcome");
			        }
			    }		


			@WebServlet("/failServlet")
			public class FailServlet extends HttpServlet {
			    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			        //Write a sentence to the page
			
			        //Set encoding
			        response.setContentType("text/html;charset=utf-8");
			        //output
			        response.getWriter().write("Login failed, wrong user name or password");
			
			    }
			
			    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			        this.doPost(request,response);
			    }
			}
  1. How to write action path of form form in login.html

     	*Resource path of virtual directory + Servlet
    
57 original articles published, 96 praised, 10000 visitors+
Private letter follow

Tags: JDBC SQL Java Druid

Posted on Tue, 11 Feb 2020 08:50:12 -0800 by Supernovas