webxml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.itheima.web.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/servlet/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<display-name>CharacterEncodingFilter</display-name>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.itheima.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<display-name>AutoLoginFilter</display-name>
<filter-name>AutoLoginFilter</filter-name>
<filter-class>com.itheima.web.filter.AutoLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AutoLoginFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping> </web-app>

domain 实体

package com.itheima.domain;

import java.io.Serializable;

public class User implements Serializable {
private String username;
private String password; public User(String username, String password) {
super();
this.username = username;
this.password = password;
} public User() {
super();
} public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} }

模仿的数据库连接

package com.itheima.domain;

import java.util.ArrayList;
import java.util.List; public class UserDB {
private static List<User> users = new ArrayList<User>();
static{
users.add(new User("陈尧","123"));
users.add(new User("李春鹏","123"));
users.add(new User("凤姐","123"));
} public static User findUser(String username,String password){
for(User u:users){
if(username.equals(u.getUsername())&&password.equals(u.getPassword())){
return u;
}
}
return null;
} public static User findUser(String username){
for(User u:users){
if(username.equals(u.getUsername())){
return u;
}
}
return null;
} }

工具类

package com.itheima.utils;

import java.io.IOException;

import org.junit.Test;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; public class Base64Util { //编码 中文 -------------5Lit5paH
public static String encode(String str){
BASE64Encoder b64= new BASE64Encoder();
return b64.encode(str.getBytes());
} //解码 5Lit5paH----中文
public static String decode(String str){
try {
BASE64Decoder b64decoder = new BASE64Decoder();
byte [] afterStr = b64decoder.decodeBuffer(str);
return new String(afterStr);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} @Test
public void testEncode(){
String str = Base64Util.encode("中文");
System.out.println(str); String newString = Base64Util.decode(str); System.out.println(newString);
}
}

md5

package com.itheima.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Encoder; public class Md5Util { //md5加密的方法
public static String encode(String old){
try {
MessageDigest md5 = MessageDigest.getInstance("md5");
byte newStr[] = md5.digest(old.getBytes()); BASE64Encoder b64= new BASE64Encoder();
return b64.encode(newStr);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}

filter

package com.itheima.web.filter;

import java.io.IOException;

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 com.itheima.domain.User;
import com.itheima.domain.UserDB;
import com.itheima.utils.Base64Util;
import com.itheima.utils.Md5Util; /**
*过滤器,用于实现自动登录过滤
*/
public class AutoLoginFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//1.如果是进行登录操作,直接放行
String resource = request.getRequestURI();//得到资源名
boolean isLogin = resource.endsWith("login.jsp");//判断是否想进行登录操作
if(!isLogin){
//不是登录才处理
//2.不是做登录操作,是否已登录过???
User user= (User)request.getSession().getAttribute("user");
if(user==null){
// 说明之前也没有登录过 //3.就要读取Cookie并进行用户名密码的验证
//3.1如何读cookie
Cookie []cookies = request.getCookies();
if(cookies==null || cookies.length==0){
response.sendRedirect(request.getContextPath()+"/login.jsp");//cookie中没有保存之前的登录信息,就要重新登录
return;
} Cookie myCookie =null;
for (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];//找一个cookie
if("loginedUser".equals(c.getName())){
//找到你想要的登录信息的cookie
myCookie = c;
break;
}
} //判断myCookie是否为空,如果不为空,说明找到登录过的用户信息的Cookie
if(myCookie!=null){
String usernameAndpassword = myCookie.getValue();//base64username_md5password
String username = usernameAndpassword.split("_")[0];//得到用户名
String password= usernameAndpassword.split("_")[1];//得到密码 //得到解码后用户名
username = Base64Util.decode(username); //根据用户名,判断该用户在数据库中是否存在
User u = UserDB.findUser(username);
if(u!=null && password.equals(Md5Util.encode(u.getPassword()))){
//你没登录,我自动给你登录了
request.getSession().setAttribute("user", u);
}
} }
} chain.doFilter(request, response);
} public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
} }

编码filter

package com.itheima.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; /**
* Servlet Filter implementation class CharacterEncodingFilter
*/
public class CharacterEncodingFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");//post乱码
response.setContentType("text/html;charset=UTF-8");//响应时没有乱码 chain.doFilter(request, response);
} public void init(FilterConfig fConfig) throws ServletException { } }

sevlet

package com.itheima.web.servlet;

import java.io.IOException;

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 com.itheima.domain.User;
import com.itheima.domain.UserDB;
import com.itheima.utils.Base64Util;
import com.itheima.utils.Md5Util;
/**
* 登录
* @author wangli
*
*/
public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.可能有乱码(不关注 ,因为过滤器已解决了)
//2.获取参数
String username = request.getParameter("username");
String password = request.getParameter("password");
String expires = request.getParameter("expires");
//3.判断用户名密码有效性
User u = UserDB.findUser(username, password); if(u==null){
//登录失败
response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/login.jsp");
response.getWriter().write("对不起,登录失败,2秒后跳到登录页");
return ;
}
//4.如果正确,将用户信息存入Session
request.getSession().setAttribute("user", u);
//5.判断是否要保存一段 时间,如果是要存储 (存什么? 用户名(编码)_密码(加密))
Cookie c = new Cookie("loginedUser",Base64Util.encode(username)+"_"+Md5Util.encode(password));//数据库UserDb中有中文 ,而cookie文件中不能有中文
//中文 可以先进行编码 ,当要使用中文时,又进行解码
//6.设置cookie的有效期
if("never".equals(expires)){
c.setMaxAge(0);
}else if("month".equals(expires)){
c.setMaxAge(30*24*60*60); //cookie存活时间 的单位:秒
}else if("year".equals(expires)){
c.setMaxAge(365*24*60*60);
}else if("forever".equals(expires)){
c.setMaxAge(Integer.MAX_VALUE);
} c.setPath(request.getContextPath()); //7.将cookie信息发送给浏览器
response.addCookie(c);
//8.进入主页面
response.setHeader("Refresh", "2;URL="+request.getContextPath()+"/index.jsp");
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response); } }

jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>XX网站</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">
--> <%
//读取cookie
%>
</head> <body>
<c:if test="${sessionScope.user==null}">
<a href="${pageContext.request.contextPath}/login.jsp">登录</a>
</c:if>
<c:if test="${sessionScope.user!=null}">
欢迎您:${user.username}<a href="#">注销</a>
</c:if>
<hr/>
XX网站
<a href="${pageContext.request.contextPath}/bbs.jsp">帖子</a>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title></title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> </head> <body>
<form action="${pageContext.request.contextPath}/servlet/LoginServlet" method="post">
用户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
登录有效期:<input type="radio" name="expires" value="never" checked="checked">无
<input type="radio" name="expires" value="month">一个月
<input type="radio" name="expires" value="year">一年
<input type="radio" name="expires" value="forever">永久<br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title></title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> <%
//读取cookie
%>
</head> <body>
${sessionScope.user.username}
</body>
</html>
05-16 14:37