码迷,mamicode.com
首页 > 其他好文 > 详细

Filter使用

时间:2020-03-10 01:40:00      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:str   web   throws   on()   block   log   public   enc   else   

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使用

标签:str   web   throws   on()   block   log   public   enc   else   

原文地址:https://www.cnblogs.com/claduxyz/p/12452848.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!