过滤器的一个应用实例:自动登录
这里我从前端往后面写,这个例子里面我没有使用到数据库,即dao层暂且忽略,账号密码我用他们相等来验证
这个例子自动登录的实现本质上就是将信息暂时存储到cookie中去,每次访问时都到cookie中去看是都存在user对象,有的话就自动登录,没有的话就进行账号密码登录。
前台页面index.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>演示利用Filter实现自动登录</title>
</head>
<body>
<h2>这是主页</h2>
<c:if test="${!empty sessionScope.error}">
${sessionScope.error}
<c:remove var="error" scope="session"/>
</c:if>
<c:if test="${empty sessionScope.user}" var="boo">
<form action="<c:url value='/LoginServlet'/>" method="post">
Name:<input type="text" name="name"><br/>
Pwd:<input type="text" name="pwd"><br/>
自动登录:
<input type="radio" name="time" value="0" checked="checked">不自动登录
<input type="radio" name="time" value="1" >1天
<input type="radio" name="time" value="7" >7天 <br/>
<input type="submit" value="登录">
</form>
</c:if>
<c:if test="${!boo}">
${user.name},欢迎你!
<a href="<c:url value='/jsps/show.jsp'/>">浏览商品</a><br/>
<a href="<c:url value='/CancelAutoLoginServlet'/>">取消自动登录</a>
</c:if>
</body>
</html>
package cn.hncu.filter;
import java.io.IOException;
import java.net.URLDecoder;
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 cn.hncu.domain.User;
public class AutoLoginFilter implements Filter {
public AutoLoginFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
if(req.getSession().getAttribute("user")==null){//还没登录,帮你自动登录
Cookie cs[] = req.getCookies();
if(cs!=null){
for(Cookie c:cs){//找"autoLogin"这个cookie
if(c.getName().equals("autoLogin")){
String str = c.getValue();
String vals[] = str.split(",");
String name = URLDecoder.decode(vals[0], "utf-8");
String pwd = URLDecoder.decode(vals[1], "utf-8");
//...//到后台验证登录是否成功(这里偷懒了,直接以两者相等来判断)
if(name.equals(pwd)){//如果成功则返回一个user对象
User user = new User();
user.setName(name);
user.setPwd(pwd);
req.getSession().setAttribute("user", user);
break;
}
}
}
}
}
chain.doFilter(req, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
CharacterFilter.java判断是否被拉入黑名单
package cn.hncu.pubs;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
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.HttpServletResponse;
public class CharacterFilter implements Filter{
private String charset;
//黑名单
private Set<String> set = new HashSet<String>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
charset = filterConfig.getInitParameter("charset");
//到数据库中把黑名单加载进来,这里简单模拟一下
set.add("127.0.0.1");
set.add("192.168.31.168");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(charset);
//以下演示黑名单过滤技术
String ip = request.getRemoteAddr();
if(set.contains(ip)){
HttpServletResponse resp = (HttpServletResponse) response;
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().println("你已被列入黑名单,不能访问!");
}else{
chain.doFilter(request, response);//放行
}
}
@Override
public void destroy() {
}
}
Servlet层
LoginServlet.java
package cn.hncu.servlet;
import java.io.IOException;
import java.net.URLEncoder;
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 cn.hncu.domain.User;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从页面接收登录信息
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
String time = request.getParameter("time");
User user = new User();
user.setName(name);
user.setPwd(pwd);
if(name!=null && name.trim().length()!=0 && pwd!=null){
if(name.equals(pwd)){//按理应该到后台去验证登录是否成功,这里偷懒了--直接以用户名和密码相同为登录成功
request.getSession().setAttribute("user", user);
//登录成功,就往客户端写一个cookie,将用户名和密码存到cookie中
//为了能够兼容中文,要进行编码
name = URLEncoder.encode(name, "utf-8");
pwd = URLEncoder.encode(pwd, "utf-8");
Cookie cookie = new Cookie("autoLogin",name+","+pwd);
cookie.setPath(request.getContextPath());//权限:本项目中的类都可以访问该cookie
//有效期
cookie.setMaxAge( 60*60*24* Integer.parseInt(time) );
response.addCookie(cookie);//存储到客户端
}else{
request.getSession().setAttribute("error", "密码错误!");
}
}else{
request.getSession().setAttribute("error", "请输入用户名!");
}
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
}
CancelAutoLoginServlet.java取消自动登录
package cn.hncu.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;
public class CancelAutoLoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("取消自动登录.....");
//取消自动登录,其实就是删除cookie
Cookie cookie = new Cookie("autoLogin","");
cookie.setPath(request.getContextPath());
cookie.setMaxAge(0);//有效期为0即是删除
response.addCookie(cookie);
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
}
值对象:User.java
package cn.hncu.domain;
public class User {
private String name;
private String pwd;
public User() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
顺便附带上web.xml
<?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_3_0.xsd" version="3.0">
<display-name></display-name>
<filter>
<filter-name>charset</filter-name>
<filter-class>cn.hncu.pubs.CharacterFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter>
<filter-name>autoLogin</filter-name>
<filter-class>cn.hncu.filter.AutoLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>charset</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>autoLogin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>cn.hncu.servlet.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>CancelAutoLoginServlet</servlet-name>
<servlet-class>cn.hncu.servlet.CancelAutoLoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CancelAutoLoginServlet</servlet-name>
<url-pattern>/CancelAutoLoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>