过滤器(Filter)应用之------设置页面缓存、用户的自动登录和敏感词过滤

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zuosixiaonengshou/article/details/53437870

PPT先贴一下,供以后查看。

Filter的应用

1

1、设置所有jsp页面不缓存:
开发步骤:
1、书写一个Filter,在其doFilter方法中添加以下代码:
HttpServletResponse resp = (HttpServletResponse)response;
resp.setHeader("expires","-1");
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control","no-cache");
chain.doFilter(request, resp);//注意是已经强转了的对像
2、将Filter配置到web.xml中。配置如下:
<filter>
<filter-name>jspcache</filter-name>
<filter-class>cn.itcast.filter.JspPageFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>jspcache</filter-name>
  <url-pattern>*.jsp</url-pattern>
  </filter-mapping>
3、打开ie,清空所有Cookie的临时文件。
4、访问本项目的jsp页面,看缓存中是否有临时文件。
5、将Filter的配置删除,然后再去看是否会出现临时文件。


2

设置某些静态的页面如html或jpg缓存。
设置url-pattern为*.html和*.jpg。
开发步骤:
1、书写一个过虑器,在doFilter中的代码如下:
HttpServletResponse response2 = (HttpServletResponse)response;
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE,4);//缓存到当前天以后的4天
long lon = c.getTimeInMillis();//获取时间的毫秒
response2.setDateHeader("expires",lon);//setDateHeader是设置时间头
chain.doFilter(request, response2);
2、将过虑器配置到web.xml中,如下:
<filter-mapping>
     <filter-name>cache</filter-name>
     <!-- 配置只能jpg文件缓存 -->
     <url-pattern>*.jpg</url-pattern>
</filter-mapping>
3、请求资源,再次请求。查看状态码为304,及缓存文件的日期为N天以后。
这是返回的状态码:HTTP/1.1 304 Not Modified

 

3

实现用户的自动登录:
解决方案:
设置一个全站拦截的过虑器。
在此过虑器中,读取用户带过来的Cookie信息,然后从中读取用户的用户名和密码,自动帮助用户登录。
即可实现自动登录功能。
 

 

canAutoLogingFilterWeb项目

当用户登录的时候可以选择自动登录多久,保存到Session和Cookie中,用过滤器来查找Cookie,进行验证,帮助用户自动登录。

 

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>
  <body>
   <c:if test="${!empty 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">
   	姓名:<input type="text" name="name"><br/>
   	密码:<input type="text" name="pwd"><br/>
   	<fieldset style="width:200px">
   		<legend>自动登录</legend>
	   	<input type="radio" name="time" value="0" checked="checked">不自动登录<br/><br/>
	   	<input type="radio" name="time" value="1">一天自动登录<br/><br/>
	   	<input type="radio" name="time" value="7">一周自动登录<br/><br/>
	   	<input type="submit" value="登录">
   	</fieldset>
   </form>
   </c:if>
   <c:if test="${!boo }">
  	欢迎您,${user}!
  	<a href="<c:url value='/jsps/show.jsp' />">信息浏览</a>
  	<a href="<c:url value='/LoginServletCancel' />">退出</a>
   </c:if>
  </body>
</html>


登录验证的LoginServlet.java

package cn.hncu.servlets;

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;

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 {
           if(request.getSession().getAttribute("user")!=null){
           /*
            * 这里补一个bug,如果登录以后,退回到登录页面,再登录一个账号,如登录失败,但另外一个账号还是在登录
            * 应该在登录之前,把原先的登录数据清除掉
            */
            request.getSession().removeAttribute("user");
            Cookie cookie=new Cookie("autoLogin","");
            cookie.setMaxAge(0);
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        }	String name =request.getParameter("name");
		String pwd  =request.getParameter("pwd");
		//本例中省去后台数据库验证,直接以name是hncu和密码长度大于6位来判断,模拟一下
		if(name.startsWith("hncu") && pwd.length()>=6){
			request.getSession().setAttribute("user", name);
			
			//下面这段专用于自动登录(把用户名和密码封装到cookie中并写到客户端浏览器中)
			//为安全考虑,这里密码应该进行加密且根据安全级别进行二次加密,还可以考虑捆绑ip或机器系统信息加密
			
			//为使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的作用域是这个项目
			String time=request.getParameter("time");
			Integer iTime=Integer.valueOf(time);
			iTime=iTime*60*60*24;//cookie默认是秒
			cookie.setMaxAge(iTime);
			response.addCookie(cookie);
		}else{
			request.getSession().setAttribute("error", "1");//登录失败
		}
		response.sendRedirect(request.getContextPath()+"/index.jsp");
	}

}


 

三个过滤器

字符编码过滤器CharacterFilter.java

package cn.hncu.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;

public class CharacterFilter implements Filter{
	private String charset;
	@Override
	public void init(FilterConfig config) throws ServletException {
		charset=config.getInitParameter("charset");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding(charset);
		response.setContentType("text/html;charset=utf-8");
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

}

 

黑名单过滤器BlackListFilter.java

package cn.hncu.filter;

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class BlackListFilter implements Filter{
	private HashSet<String> set=new HashSet<String>();
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//黑名单初始化
//		set.add("127.0.0.1");
//		set.add("10.31.1.212");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String addr=request.getRemoteAddr();
		System.out.println(addr);
		if(set.contains(addr)){
			response.getWriter().println("你已被拉入黑名单,不能登录");
		}else{
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		
	}

}


 

自动登录过滤器AutoLoginFilter.java

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;

public class AutoLoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest) request;
		
		if(req.getSession().getAttribute("user")==null){//没有登录
			//没有登录就查找cookie----autoLogin,若有则帮助登录(验证及往session中放信息),若没有则登录失败,踢回到登录界面;
			Cookie cookies[]=req.getCookies();
			if(cookies!=null){//这里也要防护一下,防止cookies为空
				for(Cookie cookie:cookies){
					//遍历cookie寻找名为autoLogin的cookie
					if(cookie.getName().equals("autoLogin")){
						String[] values=cookie.getValue().split(",");
						//拆分出来
						String name=values[0];
						String pwd=values[1];
						//由于用户名和密码是经过编码的,所以这里要进行解码
						name=URLDecoder.decode(name,"utf-8");
						pwd=URLDecoder.decode(pwd, "utf-8");
						
						//这里应该到后台数据库中验证一下,此处省略了
						if(name.startsWith("hncu")&&pwd.length()>=6){
							req.getSession().setAttribute("user", name);
						}
						break;
					}
				}
			}
			
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		
	}

}


 

web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <filter>
  	<filter-name>charset</filter-name>
  	<filter-class>cn.hncu.filter.CharacterFilter</filter-class>
  	<init-param>
  		<param-name>charset</param-name>
  		<param-value>utf-8</param-value>
  	</init-param>
  </filter>
  <filter>
  	<filter-name>BlackListFilter</filter-name>
  	<filter-class>cn.hncu.filter.BlackListFilter</filter-class>
  </filter>
  <filter>
  	<filter-name>AutoLoginFilter</filter-name>
  	<filter-class>cn.hncu.filter.AutoLoginFilter</filter-class>
  </filter>
  
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>cn.hncu.servlets.LoginServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>LoginServletCancel</servlet-name>
    <servlet-class>cn.hncu.servlets.LoginServletCancel</servlet-class>
  </servlet>


	<filter-mapping>
		<filter-name>charset</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>BlackListFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>AutoLoginFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>	
  <servlet-mapping>
    <servlet-name>LoginServletCancel</servlet-name>
    <url-pattern>/LoginServletCancel</url-pattern>
  </servlet-mapping>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


 

取消自动登录的LoginServletCancel.java

package cn.hncu.servlets;

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 LoginServletCancel 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 {
		/*
			取消自动登录
		 * 1.session
		 * 2.cookie
		 */
		request.getSession().setAttribute("user", null);
		Cookie cookie=new Cookie("autoLogin","");
		cookie.setMaxAge(0);
		cookie.setPath(request.getContextPath());
		response.addCookie(cookie);
		response.sendRedirect(request.getContextPath()+"/index.jsp");
	}

}


 

一个没什么用的显示show.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>
  <body>
   <c:if test="${!empty sessionScope.error }" >
   	登录失败,用户名或密码错误!
   	<!-- 错误信息用完一次就要清掉 -->
   <c:remove var="error" scope="session"/>
   </c:if>
   <c:if test="${empty sessionScope.user }" var="boo">
   	啦啦啦啦啦了
   </c:if>
  </body>
</html>


主页图:

登录成功图:登录成功以后,如选择了自动登录时间,则再次登录就不用输入登录信息

 

登录失败:

 

这里用的是直接把电脑ip加入黑名单:

 

 

PPT突然又出来一个包装设计模式,还是贴一下吧。

包装设计模式:

对一个类的增强,一般采取三种式
1、继承被增强的类,即实现一个子类。
2、使用动态代理处理需要增强的方法。
3、使用包装设计模式。(Java中的IO基本上都是包装设计模式)
以下是使用包装设计模式增强一个类的步骤:
1、继承需要增强的类。
2、声明需要增强有的类为自己的成员变量。
3、书写一个构造方法接收需要增强的类。
4、实现需要增强的方法。
5、实现可扩展的其他方法。
包装设计模式是指:
假定A类是B类的包装类,那么类A与类B有同样的接口,并且类A拥有类B的的实例,类A借助类B的实例来实现接口。
 

6

过虑非法语句,如脏话,和非法词组。
解决方案:
在过虑器中。包装httpServletRequest类,修改getParameter方法。即可。

 

 

canWordsFilterWeb

敏感词过滤:用过滤器(包装模式)偷偷把request的getParameter方法增强一下,把敏感词过滤掉

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>
  </head>
  
  <body >
  <div align="center">
  <h2>用户留言板</h2>
   <form action="<c:url value='/NoteServlet' />" method="post">
	   	用户名<input type="text" name="name" /><br/>
	   	<textarea rows="20" cols="40" name="info"></textarea><br/>
   		<input type="submit" value="留言" />
   </form>
  </div>
   <a href="<c:url value='/jsps/addWord.jsp'/> ">管理员添加敏感词库入口</a>
  </body>
</html>

 

请求后台的时候被过滤器拦住WordFilter.java

package cn.hncu.filter;

import java.io.IOException;
import java.util.List;

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.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import cn.hncu.pubs.WordUtils;

public class WordFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//用包装模式增强requset的功能
		request.setCharacterEncoding("utf-8");
		MyRequest req =new MyRequest((HttpServletRequest) request);
		chain.doFilter(req, response);
	}

	@Override
	public void destroy() {
	}
	
}
class MyRequest extends HttpServletRequestWrapper{
	private HttpServletRequest request;
	public MyRequest(HttpServletRequest request) {
		super(request);
		this.request=request;
	}
	@Override
	public String getParameter(String name) {
		//先用原装的方法把原始信息读取出来
		String info=super.getParameter(name);
		
		List<String> words=WordUtils.getWords();
		for(String word:words){
			if(info.contains(word)){
				String rpWord="";
				for(int i=0;i<word.length();i++){
					rpWord+="*";
				}
				info=info.replaceAll(word,rpWord);
			}
		}
		System.out.println(info);
		return info;
	}
	

}


 

内存存放敏感词工具类WordUtils.java

package cn.hncu.pubs;

import java.util.ArrayList;
import java.util.List;

public class WordUtils {
	//建一个敏感词库
	private static List<String> list=new ArrayList<String>();
	public static List<String> getWords(){
		return list;
	}
	
	//给管理员提供加载词库的方法
	public static void rbWords(){
		//这里应该把数据库中的所有信息加载进来,这里模拟一下
		list.add("sb");
		list.add("你是一条小狗");
	}
	
	//给管理员在线、实时添加敏感词提供的方法
	public static void addWord(String word){
		list.add(word);
	}
}


web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>
  <filter>
  	<filter-name>WordFilter</filter-name>
  	<filter-class>cn.hncu.filter.WordFilter</filter-class>
  </filter>
  <servlet>
    <servlet-name>NoteServlet</servlet-name>
    <servlet-class>cn.hncu.servlets.NoteServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>AdminWordsServlet</servlet-name>
    <servlet-class>cn.hncu.servlets.AdminWordsServlet</servlet-class>
  </servlet>


	<filter-mapping>
		<filter-name>WordFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  <servlet-mapping>
    <servlet-name>NoteServlet</servlet-name>
    <url-pattern>/NoteServlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>AdminWordsServlet</servlet-name>
    <url-pattern>/AdminWordsServlet</url-pattern>
  </servlet-mapping>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 


服务器NoteServlet.java

package cn.hncu.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NoteServlet 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 {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		
		String addr=request.getRemoteAddr();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time=sdf.format(new Date());
		
		String user=request.getParameter("name");
		String info=request.getParameter("info");
		out.println(time+"  "+addr+"----"+user+"说: "+info);
		
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

}


 

管理员添加敏感词界面addWord.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>
  </head>
  <body >
  <c:if test="${!empty acc }" var="acc" scope="session">
  	添加成功!
  	<c:remove var="acc" scope="session"/>
  </c:if>
  <div align="center">
  <h2>增加词库界面</h2>
   <form action="<c:url value='/AdminWordsServlet' />" method="post">
	   	敏感词<input type="text" name="word" /><br/>
   		<input type="submit" value="保存" />
   </form>
  </div>
  </body>
</html>


 

AdminWordsServlet.java

package cn.hncu.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hncu.pubs.WordUtils;

public class AdminWordsServlet 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 {
		request.setCharacterEncoding("utf-8");
		WordUtils.addWord(request.getParameter("word"));
		request.getSession().setAttribute("acc", 1);
		response.sendRedirect(request.getContextPath()+"/jsps/addWord.jsp");
	}

}


主页图:

 

管理员添加敏感词:

 

 

 

用户留言:


阅读更多
换一批

没有更多推荐了,返回首页