首页 > 其他 > 详细

过滤器

时间:2021-01-29 15:17:46      阅读:35      评论:0      收藏:0      [点我收藏+]

过滤器

  • Filter:用来过滤网站的数据
    • 登录验证、处理中文乱码等

开发步骤

  • 导包,实现javax.servlet.Filter接口

  • 重写init、doFilter、destroy三个方法

    • public class CharacterEncodingFilter implements Filter {
          public void init(FilterConfig filterConfig) throws ServletException {
              //服务器启动时初始化
              System.out.println("CharacterEncodingFilter初始化!");
          }
      
          public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
              request.setCharacterEncoding("utf-8");
              response.setCharacterEncoding("utf-8");
              response.setContentType("text/html;charset=UTF-8");
              System.out.println("CharacterEncodingFilter执行前...");
              //让请求继续走,如果不写,程序到这里就被拦截停止了
              chain.doFilter(request, response);
              System.out.println("CharacterEncodingFilter执行后...");
          }
      
          public void destroy() {
              //服务器关闭时销毁
              System.out.println("CharacterEncodingFilter销毁!");
          }
      }
      
  • 在web.xml中配置

    • <filter>
          <filter-name>CharacterEncodingFilter</filter-name>
          <filter-class>com.yhr.filter.CharacterEncodingFilter</filter-class>
      </filter>
      <filter-mapping>
          <filter-name>CharacterEncodingFilter</filter-name>
          <!--过滤/servlet/下的任何请求-->
          <url-pattern>/servlet/*</url-pattern>
      </filter-mapping>
      

登陆验证

  • Servlet:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取前端请求的参数
    String username = req.getParameter("username");
    if(username.equals("admin")){
        req.getSession().setAttribute(Constant.USER_SESSION, req.getSession().getId());
        resp.sendRedirect("/sys/success.jsp");
    } else{
        resp.sendRedirect("/error.jsp");
    }
}
  • Filter:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    if(httpRequest.getSession().getAttribute(Constant.USER_SESSION) == null){
        httpResponse.sendRedirect("/error.jsp");
    }

    chain.doFilter(request,response);
}

过滤器

原文:https://www.cnblogs.com/xiafrog/p/14344350.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!