Filter(过滤器的介绍与应用)

1、过滤器介绍

  • 用来过滤网站的数据:
    • 处理中文乱码
    • 登录验证
// 1. Filter一定要到javax.servlet包
public class CharacterEncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.print("初始化");
    }

    /* chain:链
    1. 过滤中的所有代码,在过滤器特定请求的时候都会执行
    2. 必须要经过经过过滤器计息执行
       chain.doFilter(request, response);
     */
    @Override
    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.print("执行前。。。");
        chain.doFilter(request, response); //让请求继续走,如果不写。程序到这里就被拦截停止
        System.out.print("执行后。。。");
    }

    @Override
    public void destroy() {
        System.out.print("销毁");
    }
}
  • web.xml
<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>com.study.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <!--只要是/servlet的任何请求,都会经过这个过滤器-->
    <url-pattern>/servlet/*</url-pattern>
</filter-mapping>

2、过滤器应用

用户登录之后才能进入主页,用户注销后就不能进入主页

  1. 用户登录之后,向Session中放入用户数据

    public class LoginServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 获取前端请求的参数
            String username = req.getParameter("username");
            if (username.equals("admin")) { // 登录成功
                req.getSession().setAttribute("USER_SESSION", req.getSession().getId());
                resp.sendRedirect("/sys/success.jsp");
            }else { // 登录失败
                resp.sendRedirect("/error.jsp");
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  2. 用户注销,在Session中移除用户数据

    public class LogoutServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            Object user_session = req.getSession().getAttribute("USER_SESSION");
            if (user_session !=null) {
                req.getSession().removeAttribute("USER_SESSION");
                resp.sendRedirect("/login.jsp");
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  3. 进入主页的时候判断用户是否已经登录(在过滤器中实现)

    public class SysFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
    
            Object user_session = request.getSession().getAttribute("USER_SESSION");
            if (user_session == null) {
                response.sendRedirect("/error.jsp");
            }
            chain.doFilter(request, response);
        }
    
        @Override
        public void destroy() {
        }
    }
    
  4. 注:可加工具类引用常量(本文中未引用)

    public class Constant {
        public final static String USER_SESSION = "USER_SESSION";
    }
    
  5. web.xml

    <?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_4_0.xsd"
             version="4.0"
             metadata-complete="true">
    
      <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.study.servlet.LoginServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/servlet/login</url-pattern>
      </servlet-mapping>
      
      <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.study.servlet.LogoutServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/servlet/logout</url-pattern>
      </servlet-mapping>
    
      <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.study.filter.SysFilter</filter-class>
      </filter>
      <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/sys/*</url-pattern>
      </filter-mapping>
    
    </web-app>
    
  6. /sys/success.jsp(Tomcat中Deployment的Application context配置为 / )

    <body>
        <h1>主页</h1>
        <p><a href="/servlet/logout">注销</a></p>
    </body>
    
  7. /error.jsp

    <body>
    <h1>错误</h1>
    <h3>没有权限,用户名错误</h3>
    <p><a href="/login.jsp">返回登录页面</a></p>
    </body>
    
  8. /login.jsp

    <body>
    <h1>登录</h1>
    <form action="/servlet/login" method="post">
      <input type="text" name="username">
      <input type="submit">
    </form>
    </body>
    

笔记来源:狂神说Java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值