Filter and listener in java learning

Filter and listener in java learning

0x00 Preface

In some login points or function points that can only be used after login, the user needs to log in before accessing or using these functions. However, if each servlet judges whether to log in or not, there will be a lot of duplicate code, and the efficiency is relatively low. Then we can write these codes in the filter.

There are three components in the Web: servlet, filter and listener.

I'll write about filter and listener.

0x01 filter

It is generally used to complete some unified operations, such as login authentication.

Define steps:

1. 定义一个类,实现接口Filter
2. 复写方法
3. 配置拦截路径

There are two ways to configure the interception path: Web XML and annotations.

Annotation configuration interception path


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/*")
public class FilerDemo1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException,ServletException {
        System.out.println("filterdemo执行");
        filterChain.doFilter(servletRequest,servletResponse);  //放行


    }

    @Override
    public void destroy() {

    }
}


web. XML configuration interception path

<?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">
    <filter>
        <filter-name>demo1</filter-name>  //声明名字
        <filter-class>cn.test.web.filter.FilerDemo1</filter-class> //声明对应的filter过滤器
    </filter>

    <filter-mapping>
        <filter-name>demo1</filter-name>
        <url-pattern>/*</url-pattern>     //声明filter拦截资源
    </filter-mapping>
</web-app>

You can see that the filter class needs to rewrite three methods. The functions of the three methods here are:


1. init:在服务器启动后,会创建Filter对象,然后调用init方法。只执行一次。用于加载资源

2. doFilter:每一次请求被拦截资源时,会执行。执行多次

3. destroy:在服务器关闭后,Filter对象被销毁。如果服务器是正常关闭,则会执行destroy方法。只执行一次。用于释放资源

The server will execute the filter first, and then execute the resources released by the filter. It is best to execute the code after the filter release.

The above code directly intercepts all resources. There are many ways to define filters

1. 具体资源路径: /index.jsp   只有访问index.jsp资源时,过滤器才会被执行

2. 拦截目录: /user/*	访问/user下的所有资源时,过滤器都会被执行

3. 后缀名拦截: *.jsp		访问所有后缀名为jsp资源时,过滤器都会被执行

4. 拦截所有资源:/*		访问所有资源时,过滤器都会被执行

We can define some function servlets in the background as amdin / adduserserlvlet and define a multi-layer directory. The interceptor can directly define the interception path as admin / * so that if the logged in session is carried, it can be released.

Define interception method

The interception path is defined in the annotation. The default is request, that is, the browser accesses directly. Using forwarding or other methods will be intercepted by the interceptor.

If we need to use forwarding to access resources that are not intercepted by interceptors, we can configure the value of the dispatchertypes property in the annotation.

Dispatchertypes has five attributes:

1. REQUEST:默认值。浏览器直接请求资源

2. FORWARD:转发访问资源

3. INCLUDE:包含访问资源

4. ERROR:错误跳转资源

5. ASYNC:异步访问资源

code:

package cn.test.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(value = "/*",dispatcherTypes = {DispatcherType.REQUEST,DispatcherType.FORWARD})  //定义浏览器请求和转发拦截器被执行
public class FilerDemo1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest,servletResponse);  //放行


    }

    @Override
    public void destroy() {

    }
}

If it's on the web XML, then we only need to add

web. XML configuration:

<?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">
    <filter>
        <filter-name>demo1</filter-name>
        <filter-class>cn.test.web.filter.FilerDemo1</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>demo1</filter-name>
        <url-pattern>/*</url-pattern>

        <dispatcher>REQUEST</dispatcher>
    </filter-mapping>

</web-app>

Login filter case:

package cn.test.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class loginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain) throws ServletException,IOException {
            System.out.println(req);
            //强制转换成 HttpServletRequest
            HttpServletRequest request = (HttpServletRequest) req;

            //获取资源请求路径
            String uri = request.getRequestURI();
            //判断是否包含登录相关资源路径,排除掉 css/js/图片/验证码等资源
            if(uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/fonts/") || uri.contains("/checkCodeServlet")  ){
                //包含,用户就是想登录。放行
                chain.doFilter(req,resp);
            }else{
                //不包含,需要验证用户是否登录
                //从获取session中获取user
                Object user = request.getSession().getAttribute("user");
                if(user != null){
                    //登录了。放行
                    chain.doFilter(req,resp);
                }else{
                    //没有登录。跳转登录页面

                    request.setAttribute("login_msg","您尚未登录,请登录");
                    request.getRequestDispatcher("/login.jsp").forward(request,resp);
                }
            }


            // chain.doFilter(req,resp);
        }
    

    public void init(FilterConfig config) throws ServletException {

    }

}

0x02 listener listener

Event listening mechanism:

* 事件	:一件事情

* 事件源 :事件发生的地方

* 监听器 :一个对象

* 注册监听:将事件、事件源、监听器绑定在一起。 当事件源上发生某个事件后,执行监听器代码

Listener listener implementation:

First, we need to implement the interface of servletcontextlistener. This interface does not have a well-defined implementation class and needs to be defined by ourselves.

Servletcontextlistener method:

* void contextDestroyed(ServletContextEvent sce) :ServletContext对象被销毁之前会调用该方法

* void contextInitialized(ServletContextEvent sce) :ServletContext对象创建后会调用该方法

code:

@WebListener
public class ContextLoadListeter implements servletcontextlistener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();   
        String contextConfig = servletContext.getInitParameter("configLocation");  //获取configLocation的参数
        String realPath = servletContext.getRealPath(contextConfig);  //获取路径
        try {
            FileInputStream ifs = new FileInputStream(realPath);  //读取文件
            System.out.println(ifs);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("listeter被销毁");
    }
}

web. XML configuration:

 <context-param>
        <param-name>configLocation</param-name>
        <param-value>/WEB-INF/config.xml</param-value>
    </context-param>

Listeners are generally used to load resources by default.

0x03 end

End of filter and listener.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>