Servlet学习笔记(七)—— 自己定义过滤器的编写改进:自己定义实现FilterChain...
??????筆記六中實現(xiàn)了三種過濾器:字符編碼過濾、登錄權(quán)限過濾、敏感詞過濾,可是有個缺陷就是,限定了過濾順序,而不能實現(xiàn)先進行request過濾。最后response過濾,而且中間幾項過濾的順序不能動態(tài)改變。所以這里做個改進。實現(xiàn)一個過濾順序的FilterChain。
????? 多個Filter的運行順序在這篇博文中得到非常細致的解說,總結(jié)一點。多個過濾器的運行順序是依據(jù)web.xml中不同<filter-mapping>的順序來先后運行的,比方:
<?xml version="1.0" encoding="UTF-8"?
> <web-app version="2.5" 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_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>firstFilter</filter-name> <filter-class>com.test.filter.FirstFilter</filter-class> </filter> <filter> <filter-name>secondFilter</filter-name> <filter-class>com.test.filter.SecondFilter</filter-class> </filter> <filter-mapping> <filter-name>secondFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>firstFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>firstServlet</servlet-name> <servlet-class>com.alimama.servlet.FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>firstServlet</servlet-name> <url-pattern>/firstServlet</url-pattern> </servlet-mapping> </web-app>
??????將會先運行secondFilter,再運行firstFilter。
????? 以下是截取的一段實現(xiàn)Filter接口的doFilter代碼,用戶自己定義的Filter都實現(xiàn)了這個接口:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("before invoke secondFilter's chain.doFilter() .."); chain.doFilter(request, response); System.out.println("after invoke secondFilter's chain.doFilter() .."); }
??????能夠看到第四行的chain.doFilter(request,response);這句代碼是Servlet里的Filter技術(shù)的核心,它的主要職能是將請求傳遞給下一個Filter。
不是一下子所有初始化所有的Filter對象。
??????根據(jù)這個思想,我自定義了一個FilterChain來實現(xiàn)多個過濾器的過濾順序。
//FilterChain.java package lewa;import javax.servlet.ServletRequest; import javax.servlet.ServletResponse;public class FilterChain {//private static final String[] filters={"LoginFilter","WordFilter"};private static final Filter[] filters={new LoginFilter(),new WordFilter()};private static int count=0;public void doFilter(ServletRequest request,ServletResponse response,FilterChain fc) throws InstantiationException, IllegalAccessException, Exception{if(count<filters.length){ //Class<Filter> cls=(Class<Filter>)Class.forName(filters[count]);//cls.doFilter(request, response);filters[count++].doFilter(request, response, fc);}} }
??????靜態(tài)成員變量filters里的過濾器實例的順序能夠自行定義,以后想更改過濾順序僅僅要改這個String數(shù)組就能夠。
????? 對應(yīng)的其它Filter也做了更改:
//Filter.java package lewa;import javax.servlet.ServletRequest; import javax.servlet.ServletResponse;public interface Filter {public void init();public void doFilter(ServletRequest reuqest,ServletResponse response,FilterChain fc)throws Exception;public void destroy(); }
//EncodingFilter.java package lewa;import java.io.IOException;import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse;public class EncodingFilter implements Filter{@Overridepublic void init() {// TODO Auto-generated method stub}@Overridepublic void doFilter(ServletRequest reuqest, ServletResponse response,FilterChain fc)throws InstantiationException, IllegalAccessException, Exception{// TODO Auto-generated method stubreuqest.setCharacterEncoding("UTF-8");fc.doFilter(reuqest, response,fc);response.setContentType("text/html;charset=UTF-8");}@Overridepublic void destroy() {// TODO Auto-generated method stub }}
//LoginFilter.java package lewa;import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;public class LoginFilter implements Filter{public LoginFilter(){}@Overridepublic void init() {// TODO Auto-generated method stub}@Overridepublic void doFilter(ServletRequest reuqest, ServletResponse response,FilterChain fc)throws Exception {// TODO Auto-generated method stubHttpServletRequest req=(HttpServletRequest)reuqest;HttpServletResponse resp=(HttpServletResponse)response;HttpSession session=req.getSession();if(session.getAttribute("username")==null){resp.sendRedirect("login.html");}else{fc.doFilter(reuqest, response,fc);//這里必須有一個else,不能直接是運行下一個Filter,由于假設(shè)未登陸。 那么敏感詞過濾就不必再做,并且能夠嘗試不加else,你會發(fā)現(xiàn)。未登陸前留言會跳轉(zhuǎn)到登陸界面。登陸之后再回到留言界面。 這時候count已經(jīng)不滿足count<filters.length,所以此時敏感詞過濾將不會運行。 }}@Overridepublic void destroy() {// TODO Auto-generated method stub}}
//WordFilter.java package lewa;import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern;import javax.servlet.ServletRequest; import javax.servlet.ServletResponse;public class WordFilter implements Filter{private static Pattern pattern=null;public static String str=null;private void loadKeyWordProperties(){StringBuffer patternBuffer = new StringBuffer();try{InputStream in =WordFilter.class.getClassLoader().getResourceAsStream("words.properties");Properties properties = new Properties();properties.load(in);Enumeration<?> enu=properties.propertyNames();while(enu.hasMoreElements()){patternBuffer.append((String)enu.nextElement()+"|");}patternBuffer.deleteCharAt(patternBuffer.length()-1);pattern = Pattern.compile(new String(patternBuffer.toString().getBytes("ISO-8859-1"),"UTF-8"));}catch(IOException e){e.printStackTrace();}}@Overridepublic void init() {// TODO Auto-generated method stub}@Overridepublic void doFilter(ServletRequest reuqest, ServletResponse response,FilterChain fc)throws InstantiationException, IllegalAccessException, Exception {// TODO Auto-generated method stub loadKeyWordProperties();str=reuqest.getParameter("liuyan");try{Matcher m=pattern.matcher(str);str=m.replaceAll("**");}catch(Exception e){e.printStackTrace();} fc.doFilter(reuqest, response,fc);}@Overridepublic void destroy() {// TODO Auto-generated method stub} }
?????? 最后Servlet里的代碼更改:
package lewa;import java.io.IOException; import java.io.PrintWriter;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;/*** Servlet implementation class Summary*/ public class Summary extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public Summary() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubFilter filter=new EncodingFilter();FilterChain fc=new FilterChain();try {filter.doFilter(request, response,fc);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}PrintWriter out=response.getWriter();HttpSession session=request.getSession();String name=(String) session.getAttribute("username");if(name!=null&&!"".equals(name)) {name=new String(name.getBytes("ISO-8859-1"),"UTF-8");}out.println("<html><head><title>留言板內(nèi)容</title></head><body>");out.println("用戶名:"+name);out.println("<br/>"+WordFilter.str+"</body></html>"); } }
自己定義過濾器鏈的編寫這個是源代碼的下載地址。
希望大家多多不吝賜教~~
轉(zhuǎn)載于:https://www.cnblogs.com/gccbuaa/p/6704586.html
總結(jié)
以上是生活随笔為你收集整理的Servlet学习笔记(七)—— 自己定义过滤器的编写改进:自己定义实现FilterChain...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hive环境的安装部署(完美安装)(集群
- 下一篇: 2017.4.14-afternoon