JavaWeb学习记录总结(二十九)--Servlet\Session\Cookie\Filter实现自动登录和记住密码
一、Servlet
package autologin.servlet.login;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.codec.binary.Base64;
import autologin.domain.Admin;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String oper=request.getParameter("oper");
if("pre".equals(oper)){
Cookie autoLoginCookie = getCookie(request);
if(autoLoginCookie!=null){
String value=autoLoginCookie.getValue();
if(!"".equals(value)){
String[] values=value.split(":");
if(values.length==2){
request.setAttribute("auto", 0);
request.setAttribute("name", values[0]);
request.setAttribute("pass", values[1]);
}else if(values.length==3){
request.setAttribute("name", values[0]);
request.setAttribute("pass", values[1]);
request.setAttribute("auto", values[2]);
}
}
}
request.getRequestDispatcher("./login.jsp").forward(request, response);
}else if("login".equals(oper)){
String name=request.getParameter("name");
String pass=request.getParameter("pass");
String[] rpass=request.getParameterValues("rpass");
String[] alogin=request.getParameterValues("alogin");
if("zsf".equals(name)&&"123".equals(pass)){
Admin admin=new Admin(name, pass);
//存储到session中去
request.getSession().setAttribute("admin", admin);
loginCookie(request, response, name, pass, rpass, alogin);
request.getRequestDispatcher("./index.jsp").forward(request, response);
}else{
loginCookie(request, response, name, pass, rpass, alogin);
//登录失败,重定向
response.sendRedirect("./login.do?oper=pre");
}
}else if("delete".equals(oper)){
HttpSession session=request.getSession();
session.removeAttribute("admin");
request.getRequestDispatcher("./index.jsp").forward(request, response);
}
}
private Cookie getCookie(HttpServletRequest request) {
Cookie[] cookies=request.getCookies();
Cookie autoLoginCookie=null;
if(cookies!=null&&cookies.length>0){
for(Cookie cookie:cookies){
String cookieName=cookie.getName();
if("autologin".equals(cookieName)){
autoLoginCookie=cookie;
}
}
}
return autoLoginCookie;
}
private void loginCookie(HttpServletRequest request,
HttpServletResponse response, String name, String pass,
String[] rpass, String[] alogin) {
String value="";
if(alogin!=null){
//自动登录操作
value=name+":"+md5(pass)+":"+1;
}else if(rpass!=null){
//记住密码操作
value=name+":"+md5(pass);
}
Cookie autoLoginCookie = getCookie(request);
if(autoLoginCookie==null){
autoLoginCookie=new Cookie("autologin", value);
}else{
//重新设置值
autoLoginCookie.setValue(value);
}
//加入到响应中
response.addCookie(autoLoginCookie);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public String md5(String input){
try {
MessageDigest md=MessageDigest.getInstance("md5");
byte buffer[]=md.digest(input.getBytes());
byte[] temp=Base64.encodeBase64(buffer);
System.out.println(new String(temp));
return new String(temp);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
二、Filter
package autologin.filter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.codec.binary.Base64;
import autologin.domain.Admin;
public class AutoLoginFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse) res;
String oper=request.getParameter("oper");
//判断是否是登录的准备操作,如果不是直接放行
if(!"pre".equals(oper)){
chain.doFilter(request, response);
return;
}
//1.获取session中的用户,如果有就不需要登录,如果没有直接放行
HttpSession session=request.getSession();
Admin admin=(Admin)session.getAttribute("admin");
if(admin!=null){
request.getRequestDispatcher("./index.jsp").forward(request, response);
return;
}
//2.获取Cookie中的auto标志对象,对象为空,则继续执行
Cookie autoLoginCookie=getCookie(request, "autologin");
if(autoLoginCookie==null){
chain.doFilter(request, response);
return;
}
//3.autologin name:pass:auto拆分autologin标志,返回长度如果为2,否则继续 执行
String value=autoLoginCookie.getValue();
if(value==null||"".equals(value)){
chain.doFilter(request, response);
return;
}
//4.autologin的长度等于3证明是自动登录操作
String[] values=value.split(":");
if(values!=null&&values.length==2){
chain.doFilter(request, response);
return;
}
if(values.length==3){
String name=values[0];
String pass=values[1];
//5.根据name查找这个用户的密码,pass findById Admin getObjectByName(String name)
Admin getAdmin=new Admin("zsf","123");
//根据用户名称查询得到的密码
String gpass=getAdmin.getPass();
//6判断查询出的pass与autologin标志的pass是否一样,如果不一样,就登录界面
if(md5(gpass).equals(pass)){
//7.如果一样,证明有这个用户,自动登录成功,存储到session中
session.setAttribute("admin", getAdmin);
request.getRequestDispatcher("./index.jsp").forward(request, response);
return;
}
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
private Cookie getCookie(HttpServletRequest request,String name) {
Cookie[] cookies=request.getCookies();
Cookie autoLoginCookie=null;
if(cookies!=null&&cookies.length>0){
for(Cookie cookie:cookies){
String cookieName=cookie.getName();
if(name.equals(cookieName)){
autoLoginCookie=cookie;
}
}
}
return autoLoginCookie;
}
//md5加密
public String md5(String input){
try {
//消息摘要加密类对象
MessageDigest md=MessageDigest.getInstance("md5");
//加密算法
byte buffer[]=md.digest(input.getBytes());
//安装base64进一步处理
byte[] temp=Base64.encodeBase64(buffer);
System.out.println(new String(temp));
return new String(temp);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
三、页面
(1)index.jsp
<body>
<div>
<h1>首页</h1>
</div>
<c:if test="${admin!=null }">
<div>
欢迎${admin.name }登录
<a href="${pageContext.request.contextPath }/login.do?oper=delete">注销</a>
</div>
</c:if>
<c:if test="${admin==null }">
<div>
<a href="${pageContext.request.contextPath }/login.do?oper=pre">登录</a>
</div>
</c:if>
</body>
(2)login.jsp
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
window.onload=function(){
var aloginDom=document.getElementById("alogin");
var rpassDom=document.getElementById("rpass");
//自动登录事件
aloginDom.onclick=function(){
if(this.checked){ //判断自己是否为真
if(!rpassDom.checked){//记住密码是否为真,如果为假就让它设置为真
rpassDom.checked=true;
}
}
};
//记住密码事件
rpassDom.onclick=function(){
if(aloginDom.checked){//首先判断自动登录是否为真
this.checked=true;//它永远为真
}
};
};
</script>
</head>
<body>
<div style="text-align: center;">
<h3>用户登录</h3>
<div style="text-align: center;">
<form action="${pageContext.request.contextPath }/login.do?oper=login" method="post">
<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td>用户名</td>
<td><input type="text" name="name" value="${name }" /></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="pass" value="${pass}"/></td>
</tr>
<tr>
<td colspan="2">
<c:if test="${auto==null }">
<input type="checkbox" name="rpass" id="rpass"/>记住密码
<input type="checkbox" name="alogin" id="alogin"/>自动登录
</c:if>
<c:if test="${auto==0 }">
<input type="checkbox" name="rpass" id="rpass" checked="checked"/>记住密码
<input type="checkbox" name="alogin" id="alogin"/>自动登录
</c:if>
<c:if test="${auto==1 }">
<input type="checkbox" name="rpass" id="rpass" checked="checked"/>记住密码
<input type="checkbox" name="alogin" id="alogin" checked="checked"/>自动登录
</c:if>
</td>
</tr>
<tr>
<td colspan="2">
<table width="100%"><tr>
<td align="center"><input type="submit" name="submit" value="登录"/></td>
<td align="center"><input type="reset" name="reset" value="重置"/></td>
</tr></table>
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
四、web.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>autologin</display-name>
<filter>
<filter-name>AutoLoginFilter</filter-name>
<filter-class>autologin.filter.AutoLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AutoLoginFilter</filter-name>
<url-pattern>/login.do</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>autologin.servlet.login.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
JavaWeb学习记录总结(二十九)--Servlet\Session\Cookie\Filter实现自动登录和记住密码的更多相关文章
- JavaWeb学习记录(二十)——Model1模式(javaBean+jsp)实现简单计算器案例
¨JSP技术提供了三个关于JavaBean组件的动作元素,即JSP标签,它们分别为: ¨<jsp:useBean>标签:用于在JSP页面中查找或实例化一个JavaBean组件. ¨< ...
- JavaWeb学习记录(二十二)——模式字符串与占位符
一.Java代码案例 @Test public void test10(){ int planet=7; String event="a disturban ...
- JavaWeb学习记录(二十六)——在线人数统计HttpSessionListener监听实现
一.session销毁控制层代码 public class InvalidateSession extends HttpServlet { public void doGet(HttpServletR ...
- JavaWeb学习记录(二十五)——权限管理总结
一.面向对象思想简化数据库操作 public List<Role> getObjectsByIds(List<AdminRole> adminRoles) { L ...
- JavaWeb学习记录(二十四)——获取插入数据后,自动生成的id值
public Integer insertObjects(final Goods entity) { // 定义sql语句 final String sql1 = "inser ...
- HTML5学习笔记(二十九):Cookie和Session
HTTP协议本身是无状态的,这和HTTP最初的设计是相符的,每次请求都是创建一个短连接,发送请求,得到数据后就关闭连接.即每次连接都是独立的一次连接. 这样的话,导致的问题就是当我在一个页面登陆了账号 ...
- Dynamic CRM 2013学习笔记(二十九)报表设计:reporting service 报表开发常见问题
在报表开发过程中,经常会遇到各种各样的问题,比如The report cannot be displayed. (rsProcessingAborted),一点有意义的提示都没有:再就是分页问题,经常 ...
- JavaWeb学习笔记(二十二)—— 过滤器filter
一.什么是过滤器 过滤器filter是JavaWeb三大组件之一,它与Servlet很相似!不过过滤器是用来拦截请求的,而不是处理请求的.WEB开发人员通过Filter技术,对web服务器管理的所有w ...
- Javaweb学习笔记——(二十)——————Javaweb监听器、国际化
Javaweb监听器 三大组件 *Servlet *Listener *Filter Listener:监听器 1.初次相见:A ...
随机推荐
- java枚举类
enum关键字用于定义枚举类,若枚举只有一个成员, 则可以作为一种单例模式的实现方式. 枚举类对象的属性不应允许被改动, 所以应该使用 private final 修饰. 枚举类的使用 priva ...
- [转]Putty中文乱码解决方法
from: http://www.putty.ws/putty-luanma putty使用的过程中,你是否遇到过putty出现中文乱码的情况呢?putty终端出现乱码,是情况,多数是由于系统或软件缺 ...
- Ajax get方法 IE 下乱码
每个浏览器处理编码的格式不同. ajax使用utf-8来编码发送数据,ie在发送时并没加上charset=utf-8,从而导致乱码(IE默认使用iso-8859-1编码) JavaScript代码: ...
- protected 和default的区别
default:包内可见,包外不可见 protected:包内可见,包外不可见,但是包外继承之后可见.
- 根据username查找user
返回的是一个list<User>,不过验证密码的时候,要求返回是一个user对象,如果用uniqueresult,这个是过时的方法,如果用getResultList 会得到一个列表,get ...
- self.view 的不当操作造成死循环
如题,在创建ContentView的时候,例子如下 NSString *viewClassName = NSStringFromClass([self class]); viewClassName = ...
- (转)mysql账号权限密码设置方法
原文:http://www.greensoftcode.net/techntxt/2013410134247568042483 mysql账号权限密码设置方法 我的mysql安装在c:\mysql 一 ...
- RFID Hacking①:突破门禁潜入FreeBuf大本营
某天,偶然间拿到了FreeBuf Pnig0s同学的工卡信息,终于有机会去做一些羞羞的事情了 引子 以下故事纯属虚构,如有雷同,纯属巧合. 我应聘了一个大型IT公司的"网络攻击研究部经理&q ...
- UIkit框架之UIalert(iOS 9之后就不用这个了)
IOS中UIAlertView(警告框)常用方法总结 一.初始化方法 - (instancetype)initWithTitle:(NSString *)title message:(NSString ...
- C语言数据类型在IA32中的大小
这个主要是一些常识问题,以及在使用AT&T语法汇编时会使用的编码后缀: C声明 Intel数据类型 汇编后缀 大小(byte) char 字节 b 1 short 字 w 2 int ...