过滤器

Posted 滥好人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了过滤器相关的知识,希望对你有一定的参考价值。

做过滤器:

一、做类

建一个实现javax.servlet.Filter接口的类

在doFilter()方法中编写过滤逻辑

二、做配置

在web.xml中配置<filter>和<filter-mapping>元素

 

例一:

验证页面是否登录,没登录跳转到登录页面。

1.建一个实现javax.servlet.Filter接口的类

2.在doFilter()方法中编写过滤逻辑

package com.itnba.maya.filter;

import java.io.IOException;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class StateFilter implements Filter {
    private ArrayList<String> list =new ArrayList<String>();//建一个集合,放可以不用验证身份的页面
    @Override
    public void destroy() {
        // TODO 自动生成的方法存根
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //转换类型
        HttpServletRequest req=(HttpServletRequest) request;  
        HttpServletResponse res=(HttpServletResponse) response;

          req.setCharacterEncoding("utf-8");
          res.setCharacterEncoding("utf-8");


        
        HttpSession session=req.getSession();
        //获取请求界面的路径
        String a=req.getRequestURI();//长的路径
        String b=req.getContextPath();//短的路径
        String c=a.substring(b.length());//截取路径
        
        if(list.contains(c)==false){   //要请求的不是登录页面,需要验证session;
            
            if(session.getAttribute("user")==null){//判断session是否有值,没有就转到登录页面
                res.sendRedirect("cs1.jsp");
            }
            else{
                chain.doFilter(req, res);
            }
        }
        else{
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        
        String val=arg0.getInitParameter("allowpage");//读web.xml配置中的init-param的value
        //劈开放到数组中
        String[]arr =val.split(",");
        //把数组全部放到集合里
        list.addAll(Arrays.asList(arr));
    }

}

3.在web.xml中配置<filter>和<filter-mapping>元素

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1">
    <filter>
        <filter-name>statefilter</filter-name><!--自己取的名字,跟下面的要一样-->
        <filter-class>com.itnba.maya.filter.StateFilter</filter-class><!--过滤器类的包名和类名--!>
        <init-param>
        <param-name>allowpage</param-name><!--在过滤器类中的 init(FilterConfig arg0)方法调用,获取下面的value值--!>
        <param-value>/cs1.jsp,/Cs1</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>statefilter</filter-name><!--自己取的名字,跟上面的要一样-->
        <url-pattern>/*</url-pattern><!--要过滤的页面/*代表全部-->
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

这样运行没有登录的页面,就会跳转到登录页面。

例二:

过滤敏感词,替换成***

1.建一个实现javax.servlet.Filter接口的类

2.在doFilter()方法中编写过滤逻辑,需要用内部类自己定义一request

 

package com.itnba.maya.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class Filter implements javax.servlet.Filter {
    private ArrayList<String> list =new ArrayList<>();
    

    @Override
    public void destroy() {
        // TODO 自动生成的方法存根
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse res=(HttpServletResponse) response;
    
        HttpServletRequest mreq=new MyRequest(req);
        
        //向下一个链条放行,不能用原来的request;
        chain.doFilter(mreq, res);        
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        //把敏感词放到集合里
        String val=arg0.getInitParameter("minganci");
        String[] ss = val.split(",");
        list.addAll(Arrays.asList(ss));
    }
    
    //内部类,自己定义request
    class MyRequest extends HttpServletRequestWrapper{
        private HttpServletRequest request;
        public MyRequest(HttpServletRequest request) {
            super(request);
            this.request=request;
        }
        @Override
        //重写getParameter
        public String getParameter(String name) {
            //获取提交内容
            String txt=this.request.getParameter("txt");
            
            //改集合里的敏感词
            for(String s:list){
                txt=txt.replaceAll(s, "***");
            }
            
            return txt;
        }
        
    }
}

3.在web.xml中配置<filter>和<filter-mapping>元素

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1">
    <filter>
        <filter-name>Filter</filter-name>
        <filter-class>com.itnba.maya.filter.Filter</filter-class><!--过滤器类的包名和类名--!>
        <init-param>
        <param-name>minganci</param-name><!--在过滤器类中的 init(FilterConfig arg0)方法调用,获取下面的value值--!> 
        <param-value>sb,cnm,tmd</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>Filter</filter-name>
        <url-pattern>/*</url-pattern><!--要过滤的页面/*代表全部-->
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

jsp页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="test.jsp" method="post">
<textarea name="txt" rows="5" cols="10">
sbdfdsfscnmdfdsfsdtmdfdsfsdfcnmsbtmd
</textarea>
<input type="submit" value="提交">
</form>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${param.txt }
</body>
</html>

敏感词汇都变成了***

 

以上是关于过滤器的主要内容,如果未能解决你的问题,请参考以下文章

基于内部片段的graphql过滤器(gatsbyJS)

js简洁代码片段

在底部导航栏中保存片段状态

在Pandoc lua过滤器中连接字符串片段

过滤作为 ViewPager 片段一部分的 ListView

CPNtools协议建模安全分析---实例变迁标记