[JSP+Spring] use Servlet to develop user login function = > spring

Using Servlet to develop user login function = > spring
Before transformation
Table of contents



user.java

package com.bean;
 
public class user {
	private Integer u_id;
	private String u_username;
	private String u_password;
	public user(String u_username, String u_password) {
		this.u_username = u_username;
		this.u_password = u_password;
	}
	public user() {
	}
	public Integer getU_id() {
		return u_id;
	}
	public void setU_id(Integer u_id) {
		this.u_id = u_id;
	}
	public String getU_username() {
		return u_username;
	}
	public void setU_username(String u_username) {
		this.u_username = u_username;
	}
	public String getU_password() {
		return u_password;
	}
	public void setU_password(String u_password) {
		this.u_password = u_password;
	}
}

userDaoImpl.java c3p0 to connect to the database

package com.dao;
import java.beans.PropertyVetoException;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.bean.user;
import com.mchange.v2.c3p0.ComboPooledDataSource;
 
public class userDaoImpl implements userDao {
	private static ComboPooledDataSource dpdsource;
	static {
															// Connect to database c3p0
		try {
			dpdsource = new ComboPooledDataSource();
			dpdsource.setDriverClass("com.mysql.cj.jdbc.Driver");
			dpdsource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_mybatis?serverTimezone=UTC");
			dpdsource.setUser("root");
			dpdsource.setPassword("88888888");
		} catch (PropertyVetoException e) {
			e.printStackTrace();
			System.out.println("connection failed");
		}
	}
		
	public user getuserByInfo(user u) {						// Get users from database
		
		QueryRunner qr = new QueryRunner(dpdsource);		// Using a class to manipulate database queries and return objects
	
		String sql = "select * from user1 where u_username =? and u_password = ?";
		try {
			return qr.query(sql, new BeanHandler<user>(user.class), u.getU_username(), u.getU_password());
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("Return to failure");
		}
		return null;
 
	}
 
}

userserviceImpl.java

package com.service;
import com.bean.user;
import com.dao.userDao;
import com.dao.userDaoImpl;
 
public class userServiceImpl implements userService {
 
	private userDao ud = new userDaoImpl();
 
	@Override
	public user getuserByInfo(user u) {
		
		return ud.getuserByInfo(u);
	}
 
}

userLoginService.java

package com.web;
 
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;
import javax.servlet.http.HttpSession;
 
import com.bean.user;
import com.service.userService;
import com.service.userServiceImpl;
 
@WebServlet("/userLogin")
public class userLoginService extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	public userLoginService() {
		super();
	}
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Receive form information data
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		user u = new user(username, password);
 
		// Encapsulate as user object
		// Call the service method to verify the user
		// Operate according to user authentication results
		userService us = new userServiceImpl();
		user loginUser = us.getuserByInfo(u);
		if (loginUser == null) {
			// Validation failed to login_page.jsp
			request.setAttribute("errorMsg", "Login failed");
			request.getRequestDispatcher("/login_page.jsp").forward(request, response);
		}
 
		// Verify successful login and redirect to index.jsp
		else {
			HttpSession session = request.getSession();
			session.setAttribute("user", loginUser);
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>I am home page, login success</h1>
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta charset="UTF-8">
        <title>Sign in/register</title>
        <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
 
        <!-- bootstrap framework -->
        <link href="${pageContext.request.contextPath }/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <!-- elegant icons -->
        <link href="${pageContext.request.contextPath }/css/style.css" rel="stylesheet" media="screen">
        <!-- main stylesheet -->
		<link href="${pageContext.request.contextPath }/css/main.min.css" rel="stylesheet" media="screen">
 
        <!-- jQuery -->
        <script src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
 
    </head>
    <body class="login_page">
        <div class="login_header">
        </div>
        <div class="login_register_form">
            <div class="form_wrapper animated-short" id="login_form">
                <h3 class="sepH_c"><span>Login</span> \ <a href="javascript:void(0)" class="form-switch" data-switch-form="register_form">Register</a></h3>
                <form id="loginFrom" action="${pageContext.request.contextPath }/userLogin" method="post">
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_profile"></span></span>
                        <input type="text" class="form-control" placeholder="Username" name="username">
                    </div>
                    <div class="input-group input-group-lg">
                        <span class="input-group-addon"><span class="icon_key_alt"></span></span>
                        <input type="password" class="form-control" placeholder="Password" name="password">
                    </div>
                    
                    <div>
                        <a id="errorMsg" href="javascript:void(0)" style="color: red">${errorMsg}</a>
                    </div>
                    
                    <div class="sepH_c text-right">
                        <a href="javascript:void(0)" class="small">Forgot password?</a>
                    </div>
                    <div class="form-group sepH_c">
                        <a href="javascript:doucment:loginFrom.submit()" class="btn btn-lg btn-primary btn-block">Log in</a>
                    </div>
                </form>
            </div>
            <div class="form_wrapper animated-short" id="register_form" style="display:none">
                <h3 class="sepH_c"><span>Register</span> \ <a href="javascript:void(0)" class="form-switch" data-switch-form="login_form">Login</a></h3>
                <form name = "registerForm" action="${pageContext.request.contextPath}/userRegister" method="post">
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_profile"></span></span>
                        <input type="text" class="form-control" placeholder="Username" name="username">
                    </div>
                    <div class="input-group input-group-lg sepH_a">
                        <span class="input-group-addon"><span class="icon_key_alt"></span></span>
                        <input type="password" class="form-control" placeholder="Password" name="password">
                    </div>
                    <div class="input-group input-group-lg sepH_c">
                        <span class="input-group-addon"><span class="icon_mail_alt"></span></span>
                        <input type="email" class="form-control" placeholder="Email" name="email">
                    </div>
                    <div class="form-group sepH_c">
                        <a href="javascript:doucment:registerForm.submit()" class="btn btn-lg btn-success btn-block">Register</a>
                    </div>
                </form>
            </div>
        </div>
 
        <script>
            $(function () {
                $('.form-switch').on('click', function (e) {
                    e.preventDefault();
 
                    var $switchTo = $(this).data('switchForm'),
                        $thisForm = $(this).closest('.form_wrapper');
 
                    $('.form_wrapper').removeClass('fadeInUpBig');
                    $thisForm.addClass('fadeOutDownBig');
 
                    setTimeout(function () {
                        $thisForm.removeClass('fadeOutDownBig').hide();
                        $('#' + $switchTo).show().addClass('fadeInUpBig');
                    }, 300);
 
                });
            });
        </script>
    </body>
</html>

After transformation: injection through spring

applicationContext.xml

<!-- to configure c3p0 Connection pool -->
<bean name="dataSource"
	class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
	<property name="jdbcUrl"
		value="jdbc:mysql://localhost:3306/ssm_mybatis?serverTimezone=UTC" />
	<property name="user" value="root" />
	<property name="password" value="88888888" />
</bean>
<!-- to configure dao alt + / Automatic naming-->
<bean name="userDao" class="com.dao.userDaoImpl">
	<property name="dpdsource" ref="dataSource"/>
</bean>
<!-- to configure service -->
<bean name="userService" class="com.service.userServiceImpl">
<property name="ud" ref="userDao"/>

</bean>

userLoginService.java

package com.web;
 
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;
import javax.servlet.http.HttpSession;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.bean.user;
import com.service.userService;
 
@WebServlet("/userLogin")
 
public class userLoginService extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	public userLoginService() {
		super();
	}
 
	private userService us;
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Receive form information data
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		user u = new user(username, password);
 
		// Encapsulate as user object
		// Call the service method to verify the user
		// Operate according to user authentication results
 
		// userService us = new userServiceImpl(); get from container!!!
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		us = (userService) ac.getBean("userService");
		user loginUser = us.getuserByInfo(u);
		
		if (loginUser == null) {
			// Validation failed to login_page.jsp
			request.setAttribute("errorMsg", "Login failed");
			request.getRequestDispatcher("/login_page.jsp").forward(request, response);
		}
 
		// Verify successful login and redirect to index.jsp
		else {
			HttpSession session = request.getSession();
			session.setAttribute("user", loginUser);
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

Each request will create a new container. In the web project, we only need one

useloginService.java

package com.web;
 
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;
import javax.servlet.http.HttpSession;
 
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
 
import com.bean.user;
import com.service.userService;
 
@WebServlet("/userLogin")

public class userLoginService extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	public userLoginService() {
		super();
	}
 
	private userService us;
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// Receive form information data
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		user u = new user(username, password);
 
		// Encapsulate as user object
		// Call the service method to verify the user
		// Operate according to user authentication results
 
		// userService us = new userServiceImpl(); get from container!!!
		WebApplicationContext wac =	WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		us = (userService) wac.getBean("userService");
		user loginUser = us.getuserByInfo(u);
		
		if (loginUser == null) {
			// Validation failed to login_page.jsp
			request.setAttribute("errorMsg", "Login failed");
			request.getRequestDispatcher("/login_page.jsp").forward(request, response);
		}
 
		// Verify successful login and redirect to index.jsp
		else {
			HttpSession session = request.getSession();
			session.setAttribute("user", loginUser);
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
 
}

applicationContext.xml

<!-- to configure c3p0 Connection pool -->
<bean name="dataSource"
	class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
	<property name="jdbcUrl"
		value="jdbc:mysql://localhost:3306/ssm_mybatis?serverTimezone=UTC" />
	<property name="user" value="root" />
	<property name="password" value="88888888" />
</bean>
<!-- to configure dao alt + / Automatic naming-->
<bean name="userDao" class="com.dao.userDaoImpl">
	<property name="dpdsource" ref="dataSource"/>
</bean>
<!-- to configure service -->
<bean name="userService" class="com.service.userServiceImpl">
<property name="ud" ref="userDao"/>

</bean>

DAO classes are all classes for data operations,
It is the code for adding, deleting, modifying and querying the data in the database.
DAO(Data Access Object) data access object is an object-oriented database interface, which exposes the Microsoft Jet database engine (used by Microsoft Access), and allows Visual Basic developers to connect directly to access tables through ODBC as if they were directly connected to other databases. DAO is most suitable for single system applications or small-scale local distribution.
DAO layer generally has interface and the implementation class of the interface. The interface is used to standardize the implementation class, and the implementation class is generally used to operate the database! Generally, the steps of modifying, adding and deleting database operations are very similar. A public class DAO class is written. When modifying, adding and deleting database operations, the public class DAO class is directly called.


Extended data:
DAO(Data Access Object) is a data access interface. Data access: as the name implies, it deals with databases. Sandwiched between business logic and database resources.
In the core J2EE pattern, DAO pattern is introduced as follows: in order to build a robust J2EE application, all access operations to data sources should be abstractly encapsulated in a common API. In terms of programming language, it is to establish an interface in which all transaction methods used in this application are defined. In this application, when you need to interact with the data source, you use this interface, and write a separate class to implement this interface logically corresponding to this specific data store.
Access object
DAO (data Access object) is an application programming interface (API), which exists in Microsoft's Visual Basic. It allows programmers to request Access to Microsoft's Access database. DAO is Microsoft's first object-oriented database interface. DAO objects enclose Access's Jet function. With the Jet function, it can also Access other structured query language (SQL) databases.



Tags: JSP Java Database MySQL

Posted on Mon, 11 May 2020 03:07:37 -0400 by sushant_d84