发布网友 发布时间:2022-11-20 16:37
共1个回答
热心网友 时间:2024-09-25 22:31
不管是JSP还是Servlet,其Filter过滤器都是一个东西。因为JSP的本质就是Servlet,只不过是被包装了一下,成了标准,让Web服务器都遵循这个标准来解析编译执行而已。 以下演示的就是在JSP中如何过滤脏话(Servlet的处理方式也差不多): 一、 过滤器类 package com.filter;import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;public class WordsFilter implements Filter { private Map< String, String>map = new HashMap< String, String>(); //过滤器的初始化 public void init(FilterConfig config) throws ServletException { String filePath = config.getInitParameter("filePath");//从配置文件中取得文件的相对路径 ServletContext context = config.getServletContext(); String realPath = context.getRealPath(filePath);//根据相对路径取得绝对路径 try { FileReader freader = new FileReader(realPath);//根据绝对路径,通过文件流来读取文件 BufferedReader br = new BufferedReader(freader); String line = null; while((line=br.readLine()) != null) { String []str = line.split("="); map.put(str[0], str[1]); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //乱码处理 request.setCharacterEncoding("gb2312"); response.setContentType("text/html;charset=gb2312"); HttpServletRequest HttpReq = (HttpServletRequest) request; HttpReqWrapper hrw = new HttpReqWrapper(HttpReq); hrw.setMap(map); chain.doFilter(hrw, response); } public void destroy() { System.out.println("--过滤器的销毁--"); } }二、请求包装器