JavaWeb_(Spring框架)用户登陆Spring整合到Servlet中
一、使用servlet技术开发用户登陆功能
在MySQL中准备一个user表,表中增加一条假数据
使用Servlet实现用户登陆的功能
用户登陆的<from>表单
<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>
<%@ 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>
login_page.jsp
package com.Gary.bean; public class User { private Integer u_id;
private String u_username;
private String u_password; 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;
} }
User.java
package com.Gary.dao; import java.beans.PropertyVetoException;
import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler; import com.Gary.bean.User;
import com.mchange.v2.c3p0.ComboPooledDataSource; public class UserDao { private static ComboPooledDataSource dataSource; static {
//配置c3p0
try {
//使用c3p0链接数据库
dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_spring");
dataSource.setUser("root");
dataSource.setPassword("123456");
} catch (PropertyVetoException e) { e.printStackTrace();
}
} //通过数据库获取用户
public User getUserByInfo(User u) throws SQLException { //使用dbutils操作数据库 查询并返回用户对象
QueryRunner qr = new QueryRunner(dataSource); String sql ="select * from user where u_username = ? and u_password = ?"; return qr.query(sql, new BeanHandler<User>(User.class),u.getU_username(),u.getU_password()); } }
UserDao.java
package com.Gary.service; import java.sql.SQLException; import com.Gary.bean.User;
import com.Gary.dao.UserDao; public class UserService{ private UserDao ud= new UserDao(); public User getUserByInfo(User u) throws SQLException { return ud.getUserByInfo(u);
} }
UserService.java
package com.Gary.web; import java.io.IOException;
import java.sql.SQLException; 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.Gary.bean.User;
import com.Gary.service.UserService; @WebServlet("/userLogin")
public class UserLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收表单数据
String username = request.getParameter("username");
String password = request.getParameter("password"); //封装成User对象
User u = new User();
u.setU_username(username);
u.setU_password(password); //调用service方法验证
UserService us = new UserService();
User loginUser = null;
try {
loginUser = us.getUserByInfo(u);
} catch (SQLException e) { e.printStackTrace();
} //根据用户验证结果进行操作
if(loginUser == null)
{
//验证成功登陆,并重定向到index.jsp
request.setAttribute("errorMsg", "用户名或密码错误");
request.getRequestDispatcher("/login_page.jsp").forward(request, response);
}else {
//验证失败,重定向到login_page.jsp
HttpSession session = request.getSession();
session.setAttribute("user", loginUser);
response.sendRedirect(request.getContextPath()+"/index.jsp");
} } public UserLoginServlet() {
super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response); } }
UserLoginServlet.java
修改项目
利用Spring改造项目
导入Spring的核心包,并配置Spring随项目启动
package com.Gary.bean; public class User { private Integer u_id;
private String u_username;
private String u_password; 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;
} }
User.java
package com.Gary.dao; import java.beans.PropertyVetoException;
import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler; import com.Gary.bean.User;
import com.mchange.v2.c3p0.ComboPooledDataSource; public class UserDao { /*
private static ComboPooledDataSource dataSource; static {
//配置c3p0
try {
//使用c3p0链接数据库
dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_spring");
dataSource.setUser("root");
dataSource.setPassword("123456");
} catch (PropertyVetoException e) { e.printStackTrace();
}
}
*/ private ComboPooledDataSource dataSource; public void setDataSource(ComboPooledDataSource dataSource) {
this.dataSource = dataSource;
} //通过数据库获取用户
public User getUserByInfo(User u) throws SQLException { //使用dbutils操作数据库 查询并返回用户对象
QueryRunner qr = new QueryRunner(dataSource); String sql ="select * from user where u_username = ? and u_password = ?"; return qr.query(sql, new BeanHandler<User>(User.class),u.getU_username(),u.getU_password()); } }
UserDao.java
package com.Gary.service; import java.sql.SQLException; import com.Gary.bean.User;
import com.Gary.dao.UserDao; public class UserService{ private UserDao ud= new UserDao(); public User getUserByInfo(User u) throws SQLException { return ud.getUserByInfo(u);
} public void setUd(UserDao ud) {
this.ud = ud;
} }
UserService.java
package com.Gary.web; import java.io.IOException;
import java.sql.SQLException; import javax.servlet.ServletContext;
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 org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import com.Gary.bean.User;
import com.Gary.service.UserService; @WebServlet("/userLogin")
public class UserLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L; private UserService us; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接收表单数据
String username = request.getParameter("username");
String password = request.getParameter("password"); //封装成User对象
User u = new User();
u.setU_username(username);
u.setU_password(password); //通过容器获取userService
/*ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
us = (UserService) ac.getBean("userService");*/ //在web项目中我们只需要一个spring容器 //application域 //ServletContext() 生命周期 随着web项目启动而创建 随着web项目关闭而销毁 //ServletContextListener 可以通过配置监听器来达到我们的需求,在web项目创建时候创建容器,销毁时候关闭spring容器
WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
us = (UserService)wac.getBean("userService"); //调用service方法验证
User loginUser = null;
try {
loginUser = us.getUserByInfo(u);
} catch (SQLException e) { e.printStackTrace();
} //根据用户验证结果进行操作
if(loginUser == null)
{
//验证成功登陆,并重定向到index.jsp
request.setAttribute("errorMsg", "用户名或密码错误");
request.getRequestDispatcher("/login_page.jsp").forward(request, response);
}else {
//验证失败,重定向到login_page.jsp
HttpSession session = request.getSession();
session.setAttribute("user", loginUser);
response.sendRedirect(request.getContextPath()+"/index.jsp");
} } public UserLoginServlet() {
super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response); } }
UserLoginServlet.java
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <!-- 配置 dataSource -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm_spring"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean> <!-- 配置 dao -->
<bean name="userDao" class="com.Gary.dao.UserDao">
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 配置 service -->
<bean name="userService" class="com.Gary.service.UserService">
<property name="ud" ref="userDao"/>
</bean> </beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ssm_spring_servlet</display-name> <!-- 配置监听器,在web项目启动后让spring启动 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 读取spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
web.xml
<%@ 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>
login_page.jsp
JavaWeb_(Spring框架)用户登陆Spring整合到Servlet中的更多相关文章
- Spring框架系列(2) - Spring简单例子引入Spring要点
上文中我们简单介绍了Spring和Spring Framework的组件,那么这些Spring Framework组件是如何配合工作的呢?本文主要承接上文,向你展示Spring Framework组件 ...
- Spring框架系列(6) - Spring IOC实现原理详解之IOC体系结构设计
在对IoC有了初步的认知后,我们开始对IOC的实现原理进行深入理解.本文将帮助你站在设计者的角度去看IOC最顶层的结构设计.@pdai Spring框架系列(6) - Spring IOC实现原理详解 ...
- Spring框架系列(7) - Spring IOC实现原理详解之IOC初始化流程
上文,我们看了IOC设计要点和设计结构:紧接着这篇,我们可以看下源码的实现了:Spring如何实现将资源配置(以xml配置为例)通过加载,解析,生成BeanDefination并注册到IoC容器中的. ...
- Spring框架系列(8) - Spring IOC实现原理详解之Bean实例化(生命周期,循环依赖等)
上文,我们看了IOC设计要点和设计结构:以及Spring如何实现将资源配置(以xml配置为例)通过加载,解析,生成BeanDefination并注册到IoC容器中的:容器中存放的是Bean的定义即Be ...
- Spring框架系列(9) - Spring AOP实现原理详解之AOP切面的实现
前文,我们分析了Spring IOC的初始化过程和Bean的生命周期等,而Spring AOP也是基于IOC的Bean加载来实现的.本文主要介绍Spring AOP原理解析的切面实现过程(将切面类的所 ...
- Spring框架系列(10) - Spring AOP实现原理详解之AOP代理的创建
上文我们介绍了Spring AOP原理解析的切面实现过程(将切面类的所有切面方法根据使用的注解生成对应Advice,并将Advice连同切入点匹配器和切面类等信息一并封装到Advisor).本文在此基 ...
- Spring框架系列(11) - Spring AOP实现原理详解之Cglib代理实现
我们在前文中已经介绍了SpringAOP的切面实现和创建动态代理的过程,那么动态代理是如何工作的呢?本文主要介绍Cglib动态代理的案例和SpringAOP实现的原理.@pdai Spring框架系列 ...
- Spring框架系列(12) - Spring AOP实现原理详解之JDK代理实现
上文我们学习了SpringAOP Cglib动态代理的实现,本文主要是SpringAOP JDK动态代理的案例和实现部分.@pdai Spring框架系列(12) - Spring AOP实现原理详解 ...
- Spring 框架系列之 JDBC 整合实例
微信公众号:compassblog 欢迎关注.转发,互相学习,共同进步! 有任何问题,请后台留言联系! 1.Spring框架整合 DAO 模板 JDBC:org.springframework.jdb ...
随机推荐
- bat实现守护程序保证平台正常运行
1.systeminfo查看系统最近一次重启时间: 2.杀进程: :start taskkill /f /im "xx.exe" goto start "xx.exe&q ...
- less学习大纲总结
1.注释的区别 /**/ //2.变量的命名 @+变量名 如:@f_width 引用的时候也要带上@ 符号3.混合 可带参数 默认带值4.匹配模式 相当于js里的if,但不完全是 用于符号条件的匹配 ...
- element的Dialog组件踩坑
在一个组件页面中需要有一个弹窗,为了代码简洁我把弹窗封装成一个组件方便重复调用 描述大致是一个父组件,里面有一个按钮还有一个子组件(弹窗),点击按钮让弹窗出来,弹窗自带的有关闭功能,点击关闭以后再点击 ...
- BPM软件_财务报销流程管理解决方案_K2工作流引擎
财务报销,对任何企业都是日常运营中重要的一个环节.但报销流程周期长,反复签字手续繁杂,报销过程不透明 ,单据归档保存.检索困难等问题也让员工头疼.为了解决这些困扰,财务报销流程电子化一时成为热门之选. ...
- ubuntu16.04安装aquatone
很坑 网上的那些教程 不知道怎么搞得.... 误人子弟 首先 一台服务器 ubuntu16.04 首先aquatone github https://github.com/michenr ...
- iOS开发 iOS10推送必看(基础篇)-转
iOS10更新之后,推送也是做了一些小小的修改,下面我就给大家仔细说说.希望看完我的这篇文章,对大家有所帮助. 一.简单入门篇---看完就可以简单适配完了 相对简单的推送证书以及环境的问题,我就不在这 ...
- Marketing Cloud的contact merge机制
Marketing Cloud的contact支持多种多样的数据源,如下图所示: SAP Hybris Commerce SAP ERP SAP Cloud for Customer SAP Gigy ...
- Echarts如何添加鼠标点击事件?防止重复触发点击事件
Echarts如何添加鼠标点击事件? 1.通常我们只使用了以下代码,通过配置项和数据显示图表. var myChart = echarts.init(document.getElementById(' ...
- Java基于Redis的分布式锁
分布式锁,其实最终还是要保证锁(数据)的一致性,说到数据一致性,基于ZK,ETCD数据一致性中间件做分数是锁,才是王道.但是Redis也能满足最基本的需求. 参考: https://www.cnblo ...
- airtest使用
airtest Airtest是网易开发的手机UI界面自动化测试工具 通过截图功能操作手机虽然方便,但是截图涉及到分辨率的问题,代码不能在不同的手机上通用. 可以用来开发手机App爬虫 使用先抓大再抓 ...