过滤器&监听器

一、Filter(重点)

Filter:过滤器,用来过滤网站的数据;

  • 处理中文乱码
  • 登录验证...

filter开发步骤:

  1. 导包

    • 导包不要错

  2. 编写过滤器

    • 实现filter接口,重写对应的方法即可
public class CharacterEncodingFilter implements Filter{

    //初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现!
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化");
    }

    //chain:链
    /*
    1.过滤中的所有代码,在过滤特定请求的时候都会执行
    2.必须要让过滤器继续同行
    */
    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执行后。。。");
    }

    //销毁:web服务器关闭的时候,过滤器会销毁
    public void destroy() {
        System.out.println("CharacterEncodingFilter销毁");
    }
}
  1. 在web.xml中配置filter
<?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">

    <servlet>
        <servlet-name>showServlet</servlet-name>
        <servlet-class>com.jhoves.servlet.ShowServlet</servlet-class>
    </servlet>
    <!--这种就会经过过滤器-->
    <servlet-mapping>
        <servlet-name>showServlet</servlet-name>
        <url-pattern>/servlet/show</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>showServlet</servlet-name>
        <url-pattern>/show</url-pattern>
    </servlet-mapping>
   
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.jhoves.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <!--只要是 /servlet的任何请求,都会经过这个过滤器-->
        <url-pattern>/servlet/*</url-pattern>
    </filter-mapping>
</web-app>

二、监听器

实现一个监听器的接口;(有n种)

1、编写一个监听器

  • 实现监听器的一个接口
//统计网站在线人数:统计session
public class OnlineCountListener implements HttpSessionListener{

    //创建session监听
    //一旦创建session就会触发一次这个事件!
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer OnlineCount = (Integer) ctx.getAttribute("OnlineCount");
        if(OnlineCount==null){
            OnlineCount = new Integer(1);
        }else{
            int count = OnlineCount.intValue();
            OnlineCount = new Integer(count+1);
        }

        ctx.setAttribute("OnlineCount",OnlineCount);
        System.out.println(se.getSession().getId());

    }
    //销毁session监听
    //一旦销毁session就会触发一次这个事件!
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer OnlineCount = (Integer) ctx.getAttribute("OnlineCount");
        if(OnlineCount==null){
            OnlineCount = new Integer(0);
        }else{
            int count = OnlineCount.intValue();
            OnlineCount = new Integer(count-1);
        }

        ctx.setAttribute("OnlineCount",OnlineCount);

    }
}

2、web.xml中注册监听器

<!--注册监听器-->
    <listener>
        <listener-class>com.jhoves.listener.OnlineCountListener</listener-class>
    </listener>

3、看情况是否使用

三、过滤器应用

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

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(Constant.USER_SESSION,req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2.进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!

//ServletRequest HttpServletRequest
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;

if(request.getSession().getAttribute(Constant.USER_SESSION)==null){
	response.sendRedirect("/error.jsp");
}
        
chain.doFilter(request,response);
posted @ 2022-03-20 20:49  JHoves  阅读(35)  评论(0)    收藏  举报