一、使用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中的更多相关文章

  1. Spring框架系列(2) - Spring简单例子引入Spring要点

    上文中我们简单介绍了Spring和Spring Framework的组件,那么这些Spring Framework组件是如何配合工作的呢?本文主要承接上文,向你展示Spring Framework组件 ...

  2. Spring框架系列(6) - Spring IOC实现原理详解之IOC体系结构设计

    在对IoC有了初步的认知后,我们开始对IOC的实现原理进行深入理解.本文将帮助你站在设计者的角度去看IOC最顶层的结构设计.@pdai Spring框架系列(6) - Spring IOC实现原理详解 ...

  3. Spring框架系列(7) - Spring IOC实现原理详解之IOC初始化流程

    上文,我们看了IOC设计要点和设计结构:紧接着这篇,我们可以看下源码的实现了:Spring如何实现将资源配置(以xml配置为例)通过加载,解析,生成BeanDefination并注册到IoC容器中的. ...

  4. Spring框架系列(8) - Spring IOC实现原理详解之Bean实例化(生命周期,循环依赖等)

    上文,我们看了IOC设计要点和设计结构:以及Spring如何实现将资源配置(以xml配置为例)通过加载,解析,生成BeanDefination并注册到IoC容器中的:容器中存放的是Bean的定义即Be ...

  5. Spring框架系列(9) - Spring AOP实现原理详解之AOP切面的实现

    前文,我们分析了Spring IOC的初始化过程和Bean的生命周期等,而Spring AOP也是基于IOC的Bean加载来实现的.本文主要介绍Spring AOP原理解析的切面实现过程(将切面类的所 ...

  6. Spring框架系列(10) - Spring AOP实现原理详解之AOP代理的创建

    上文我们介绍了Spring AOP原理解析的切面实现过程(将切面类的所有切面方法根据使用的注解生成对应Advice,并将Advice连同切入点匹配器和切面类等信息一并封装到Advisor).本文在此基 ...

  7. Spring框架系列(11) - Spring AOP实现原理详解之Cglib代理实现

    我们在前文中已经介绍了SpringAOP的切面实现和创建动态代理的过程,那么动态代理是如何工作的呢?本文主要介绍Cglib动态代理的案例和SpringAOP实现的原理.@pdai Spring框架系列 ...

  8. Spring框架系列(12) - Spring AOP实现原理详解之JDK代理实现

    上文我们学习了SpringAOP Cglib动态代理的实现,本文主要是SpringAOP JDK动态代理的案例和实现部分.@pdai Spring框架系列(12) - Spring AOP实现原理详解 ...

  9. Spring 框架系列之 JDBC 整合实例

    微信公众号:compassblog 欢迎关注.转发,互相学习,共同进步! 有任何问题,请后台留言联系! 1.Spring框架整合 DAO 模板 JDBC:org.springframework.jdb ...

随机推荐

  1. 本地虚拟机NAT模式下怎么设置才可以访问外网

    记:因为我要在本机虚拟机上安装Docker,结果发现虚拟机环境不能上网,是主机模式.我要调成net模式下才可以访问外网,这就需要怎么设置.下面文章记录一下. 在本机安装VMware软件后,系统中会自动 ...

  2. 关于linux中关在共享文件的NFS 提示错误解决办法

    0. 查看挂载情况命令 : findmnt 1. 如果在客户机上遇到如下这样的提示错误,有可能的原因是因为没有安装nfs-utils   只需要yum install nfs-utils   就解决了 ...

  3. CUDA 笔记

    名词解释 SM :Streaming Multiprocessor    而 Block 大致就是对应到 SM     所有的blocks 按照流水线被送到6个SM中进行计算 在 Compute Ca ...

  4. ArrayList和CopyOnWriteArrayList(转载)

    这篇文章的目的如下: 了解一下ArrayList和CopyOnWriteArrayList的增删改查实现原理 看看为什么说ArrayList查询快而增删慢? CopyOnWriteArrayList为 ...

  5. SpringCloud"灰度部署"——动态刷新网关配置

    通过Acutator和SpringCloudConfig完成"灰度部署"——动态刷新网关路由配置 先声明下,我这个可能是冒牌的灰度部署,技术有限,纯粹个人笔记分享. 前段时间接到了 ...

  6. React/Refs and this DOM

    Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素. 何时使用Refs 管理焦点,文本选择或媒体播放. 触发强制动画. 集成第三方 DOM 库. 避 ...

  7. vue的$nextTick使用后的js代码执行顺序问题

    一.问题产生背景: 父组件已经获得子组件实例,并能直接触发子组件的方法,在父组件中调用了子组件的两个方法 // 父组件调用子组件,this.picker是获取的子组件整个实例,先调用update,再调 ...

  8. 转: 解决idea工具下tomcat中文乱码问题

    在运行/调试 配置对话框的Startup/Connection面板中, 勾选Pass environment variables. 并添加一个environment variable, Name填 J ...

  9. 华擎 J3455 主板装 Linux 系统

    入手华擎J3455 ITX 主板,装备安装一个 redhat 来学习linux,及做一个家庭 web 服务器.但安装过程一波三折. 问题1.使用U盘引导不了,首先华擎这块板是 UEFI 板,用之前的老 ...

  10. FormCollection使用

    FormCollection用来在controller中获取页面表单元素的数据.它是表单元素的集合,包括<input type="submit" />元素. 用法举例: ...