【JSP+Spring】使用Servlet开发用户登录功能 => spring

与世无争的帅哥 提交于 2020-10-27 16:16:47

使用Servlet开发用户登录功能 => spring
改造前
目录 



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来连接数据库

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 {
															// 连接数据库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("连接失败");
		}
	}
		
	public user getuserByInfo(user u) {						// 通过数据库获取用户
		
		QueryRunner qr = new QueryRunner(dpdsource);		// 使用一个类 操作数据库 查询并返回对象
	
		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 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 {
		// 接收表单信息数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		user u = new user(username, password);
 
		// 封装成user对象
		// 调用service方法验证用户
		// 根据用户验证结果进行操作
		userService us = new userServiceImpl();
		user loginUser = us.getuserByInfo(u);
		if (loginUser == null) {
			// 验证失败到login_page.jsp
			request.setAttribute("errorMsg", "登陆失败");
			request.getRequestDispatcher("/login_page.jsp").forward(request, response);
		}
 
		// 验证成功登陆,重定向到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>我是首页,登录成功</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>登录/注册</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>

改造后 :通过spring注入

applicationContext.xml

<!-- 配置c3p0连接池 -->
<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>
<!-- 配置dao alt + / 自动命名-->
<bean name="userDao" class="com.dao.userDaoImpl">
	<property name="dpdsource" ref="dataSource"/>
</bean>
<!-- 配置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 {
		// 接收表单信息数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		user u = new user(username, password);
 
		// 封装成user对象
		// 调用service方法验证用户
		// 根据用户验证结果进行操作
 
		// userService us = new userServiceImpl();通过容器获取!!!
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		us = (userService) ac.getBean("userService");
		user loginUser = us.getuserByInfo(u);
		
		if (loginUser == null) {
			// 验证失败到login_page.jsp
			request.setAttribute("errorMsg", "登陆失败");
			request.getRequestDispatcher("/login_page.jsp").forward(request, response);
		}
 
		// 验证成功登陆,重定向到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);
	}
}

每次请求都会新创建一个容器,在web项目中我们只需要一个

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 {
		// 接收表单信息数据
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		user u = new user(username, password);
 
		// 封装成user对象
		// 调用service方法验证用户
		// 根据用户验证结果进行操作
 
		// userService us = new userServiceImpl();通过容器获取!!!
		WebApplicationContext wac =	WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		us = (userService) wac.getBean("userService");
		user loginUser = us.getuserByInfo(u);
		
		if (loginUser == null) {
			// 验证失败到login_page.jsp
			request.setAttribute("errorMsg", "登陆失败");
			request.getRequestDispatcher("/login_page.jsp").forward(request, response);
		}
 
		// 验证成功登陆,重定向到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

<!-- 配置c3p0连接池 -->
<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>
<!-- 配置dao alt + / 自动命名-->
<bean name="userDao" class="com.dao.userDaoImpl">
	<property name="dpdsource" ref="dataSource"/>
</bean>
<!-- 配置service -->
<bean name="userService" class="com.service.userServiceImpl">
<property name="ud" ref="userDao"/>

</bean>

DAO类都是进行数据操作的类,
是对于数据库中的数据做增删改查等操作的代码。
DAO(Data Access Object) 数据访问对象是一个面向对象的数据库接口,它显露了 Microsoft Jet 数据库引擎(由 Microsoft Access 所使用),并允许 Visual Basic 开发者通过 ODBC 像直接连接到其他数据库一样,直接连接到 Access 表。DAO 最适用于单系统应用程序或小范围本地分布使用。
DAO层一般有接口和该接口的实现类,接口用于规范实现类,实现类一般用于用于操作数据库! 一般操作修改,添加,删除数据库操作的步骤很相似,就写了一个公共类DAO类 ,修改,添加,删除数据库操作时直接调用公共类DAO类。


扩展资料:
DAO(Data Access Object)是一个数据访问接口,数据访问:顾名思义就是与数据库打交道。夹在业务逻辑与数据库资源中间。
在核心J2EE模式中是这样介绍DAO模式的:为了建立一个健壮的J2EE应用,应该将所有对数据源的访问操作抽象封装在一个公共API中。用程序设计的语言来说,就是建立一个接口,接口中定义了此应用程序中将会用到的所有事务方法。在这个应用程序中,当需要和数据源进行交互的时候则使用这个接口,并且编写一个单独的类来实现这个接口在逻辑上对应这个特定的数据存储。
访问对象
DAO(数据访问对象)是一种应用程序编程接口(API),存在于微软的Visual Basic中,它允许程序员请求对微软的Access数据库的访问。DAO是微软的第一个面向对象的数据库接口。DAO对象封闭了Access的Jet函数。通过Jet函数,它还可以访问其他的结构化查询语言(SQL)数据库。



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!