Filter使用

Posted claduxyz

tags:

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

Filter使用

说白了就是在servlet执行前增加一步动作,获取requset中的参数来做例如中文乱码、过滤敏感词、判断是否登陆的操作。

初始化

  • xml
    <filter>
        <filter-name>charaterFilter</filter-name>
        <filter-class>com.claudxyz.filter.CharacterFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>charaterFilter</filter-name>
        <url-pattern>/login</url-pattern>
    </filter-mapping>
  • 注解
@WebFilter("/login")
public class CharacterFilter implements Filter {

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

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

应用场景

  • 处理中文乱码
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("UTF-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }
  • 过滤敏感词
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("UTF-8");
        String name = servletRequest.getParameter("name");
        name = name.replaceAll("少儿不宜","****");
        System.out.println(name);
        filterChain.doFilter(servletRequest,servletResponse);
    }
  • 控制资源访问权限
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //通过httpServletRequest获取httpsession
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        HttpSession httpSession = httpServletRequest.getSession();
        //从session中获取登录时存放的用户名
        String name = (String) httpSession.getAttribute("name");
        //通过session中是否包含name值判断是重新登陆还是跳转资源页面
        if(StringUtils.isEmpty(name)){
            httpServletResponse.sendRedirect("/login.jsp");
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

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

JS常用代码片段2-值得收藏

将多个输出中的hls属性设置为单独的片段代码

filter与servlet

java---servlet与filter的联系与区别

php代码片段: sendFile/videoStream/sendEmail/phpexcel/ffmpeg/zip

text 此片段用于以下知识库文章 - http://kb.wpbeaverbuilder.com/article/591-create-a-filter-to-customize-the-di