当前位置:网站首页>Servlet -- servlet advanced API, filter, listener

Servlet -- servlet advanced API, filter, listener

2020-12-07 18:10:05 osc_ f9krav3q

Servlet Initialization process 、ServletConfig

Every Servlet All must be Web Container reading Servlet Setting information , Initialization etc. , In order to generate the corresponding Servlet example . For each Servlet Setting information of ,Web The container will generate a ServletConfig As a representative object .

stay Servlet On the interface , Defines and Servlet Life cycle and request service init,service,destroy Three methods . Every time a request comes to the container , Will produce HttpServletRequest,HttpServletResponse object , And call service Method is passed in as a parameter .

stay Web After the container starts , According to the above , Will produce a ServletConfig object , And then call init Method and will produce ServletConfig Object is passed into it , This process is creating Servlet After the instance, only once , And then every request came , Just call Servlet Of service Methods to service .

Servlet Class diagram :
 Picture description here

stay Java in , When we want to do something after the object is instantiated , The constructor must be defined , However, in JavaWeb Middle is not , When we want to use ServletConfig When you come to do something , We need to redefine init Method , Because in Web in , After the object is instantiated , The container has not yet called init Methods the incoming ServletConfig, So if we use... In the constructor ServletConfig Words , There is no such object .

Before we get it, we're in Servlet Information about the parameters set in the (WebServlet Things set up in ), We use... Directly getInitParameterNames, getInitParameterName Other methods , In fact, these methods are encapsulated , The purpose is not to make us realize ServletConfig this API, actually ,GenericServlet It includes Servlet and ServletConfig A simple implementation of the defined method , Such as :

public String getInitParameter(String name){
    return getServletConfig.getInitParameter(name);
}

wait . So in general, we're getting Servlet The initial parameters of the , Will directly write the code as getInitParameter.

According to what I said above , because ServletConfig The container call has parameters init Method is called , So if we want to use ServletConfig Do some initialization , We need to be in parameterless init Methods , Let's take a look at the source code :

private transient ServletConfig config;
public void init(ServletConfig config) throw ServletException {
    this.config = config;
    this.init();
}

We can see clearly in init A series of initialization actions defined in , Get in ServletConfig All instances of will be executed after .
As for the Servlet When to use initialization parameters in , I think it works with C Linguistic #define Quite .


ServletContext

ServletContext Object can be used to get the requested resource URL, Set and store properties , Application initialization parameters , Dynamic setting Servlet example .

ServletContext In fact, it's not a single Servlet On behalf of , When the whole Web Application loading Web After container , The container will produce a ServletContext Object as a representative of the entire application , And set to ServletConfig, adopt ServletConfig Of getServletContext Method can obtain ServletContext object .


getRequestDispatcher()

To obtain RequestDispatcher example , The path used must be specified as “/” As the beginning , This “/” Represents the application environment and directory .

With “/” As a starting point, it's called the environment relative path , Not to “/” This is called the request relative path at the beginning . actually getRequestDispatcher At the time of realization , If the environment relative path , It is directly entrusted to ServletContext Of getRequestDispatcher, If the request relative path , It is directly converted to the environment relative path , To entrust to ServletContext Of getRequestDispatcher Method .


getResourcePaths()

It can help us know Web What files are in a directory of the application , The path used must be specified as “/” As the beginning , Represents the root directory relative to the application environment .


getResourceAsStream()

If you want to Web Read the content of a file in the application program , You can use getResourceAsStream(), Its specified path also takes “/” start , The running result will return InputStream example .


ServletContext event , Monitor

Monitor : When we want to be in HttpServletRequest,HttpSession,ServletContext Object to generate , When destruction or related properties occur, do something we want to do , We need to implement the corresponding listener .


ServletContextListener

ServletContextListener yes “ Life cycle monitor ”, If you want to know Web When the application has been initialized , Or about to be destroyed , You can implement this class .

In this interface , Two methods are defined , Namely :

public interface ServletContextListen extends EventListener {
   
         
    public void contextInitialized(ServletContextEvent sce);
    public void contextDestroyed(ServletContextEvent sce);
}

stay Web Just before or after the application is destroyed , Would call ServletContextListener Implementation class corresponding to contextInitialized Method or contextDestroyed Method . Can be in contextInitialized To implement the resource preparation action after application initialization , stay contextDestroyed The release action of application resources is realized in .

ServletContextListener You can use it directly @WebListener mark , And it has to happen ServletContextListener Interface . When the container calls a method in this interface , It will pass in ServletContextEvent, It encapsulates ServletContext, Can pass ServletContextEvent Of getServletContext Method acquisition ServletContext, adopt ServletContext Of getInitParameter Method to read the initial parameters .

Throughout Web During the application lifecycle ,Servlet The data to be shared can be set to ServletContext attribute . because ServletContext stay Web The application will exist for as long as it lives , So set to ServletContext Attribute data , Unless you take the initiative to remove , Otherwise, it's been living with Web In the application .

because @WebListener There is no property to set the initial parameter , Therefore, it is only applicable to the case without setting the initial parameters . If you need to set the initial parameters , You can do it again Web.xml Set in .

<context-param>
    <param-name>AVATAR</param-name>
    <param-value>/avatars</param-value>
</context-param>

ServletContextAttributeListener

This class is a property change listener , If you want the object to be set , remove , Or replace ServletContext attribute , You can receive a notification to do something , You can implement this class .


HttpSession event 、 Monitor

HttpSessionListener

Life cycle monitor , And ServletContext Life cycle monitors function similar , If you want to HttpSession When an object is created or ended , Do some corresponding actions , You can achieve this kind of .

public interface HttpSessionListener extends EventListener {
   
           
    public void sessionCreated(HttpSessionEvent se);
    public void sessionDestroyed(HttpSessionEvent se);
}

I will not elaborate on the specific functions of the method , contrast ServletContextListener Just go , We can use the incoming HttpSessionEvent, Use getSession obtain HttpSession, To create or end processing operations for session objects .

Now there's a real application scenario , Some websites try to prevent users from logging in repeatedly , A field in the database represents whether the user is logged in or not , After the user logs in, the field information is set in the database , Represents that the user has logged in , After the user logs off, the field is reset . If the user is already logged in , Try to log in with another browser before logging out , The application will check the fields in the data that represent login or not , If it is found that it has been set to login , Then refuse to log in repeatedly . Now there's a problem , If the user accidentally closes the browser before logging off , The logout operation did not actually run , The fields in the database that represent login or not will not be reset . So it can be done HttpSessionListener, because HttpSession There's a life span , When a container destroys something HttpSession when , Will call sessionDestoryed, We can reset the login field of the database in it .


HttpSessionAttributeListener

The function of this class and ServletContextAttributeListener It's very similar , Let's take a look at the source code of the interface :

public interface HttpSessionAttributeListener extends EventListener {
   
            
    public void attributeAdded (HttpSessionBindEvent se);
    public void attributeRemoved (HttpSessionBindEvent se);
    public void attributeReplaced (HttpSessionBindEvent se);
}

HttpSessionBindListener

Object binding listener , If one is about to join HttpSession Property object for , Hope to set to HttpSession To become an attribute or from HttpSession In one place , You can receive HttpSession The notice of , You can let the object implement HttpSessionBindListener Interface . See this , Is there any confusion between this class and the previous one , At first glance , These two classes implement the same function . I also searched some information on the Internet , Just untied the confusion in my heart . We are using HttpSessionBindListener When , You want to set an object to HttpSession Attribute and perform on it “ monitor ”, Then we must implement this class when we implement it HttpSessionBindListener This interface , Then bind to HttpSession Only on can monitor be realized . However, when we use HttpSessionAttributeListener Interface , No matter what object , As long as we bind it to HttpSession On , You can do it “ monitor ”.

package SessionListenerDemo2;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

/**
 * Created by hg_yi on 17-6-5.
 */
public class User implements HttpSessionBindingListener {
   
             
    private String name;
    private String data;

    public User(String name) {
        this.name = name;
    }

    public void valueBound(HttpSessionBindingEvent event) {
        this.data = name + " Operations from the database ...";
    }

    public void valueUnbound(HttpSessionBindingEvent event) { }

    public String getData() {
        return data;
    }

    public String getName() {
        return name;
    }
}

When we want to use HttpSessionBindListener Yes User monitor , So we're setting it to HttpSession When attributes , You need to make it happen HttpSessionBindListener Interface .


HttpServletRequest event 、 Monitor

ServletRequestListener

Life cycle monitor , Which one do you prefer?Hear the name , I think everyone already knows what it does , Take a look at the source code directly :

public interface ServletRequestListener extends EventListener {
   
              
    public void requestDestroyed(ServletRequestEvent sre);
    public void requestInitialized(ServletRequestEvent sre);
}

ServletRequestAttributeListener

Property change listener , Its effect is no different from the above , The parameter passed in the method is ServletRequestAttributeEvent.
ServletRequestAttributeEvent There is one getName Method , Its function is to get the name specified when the property is set or removed , and getValue You can get the object when the property is set or removed .


Life cycle monitor , Property change listener , All must use @WebListener Or in the web.xml Set in , The container will know to load , Read listener settings .


filter

Before we talk about filters , Let's make a concept clear :
Call... In the container Servlet Of service Before method ,Servlet I didn't know there was a request coming , call service After method , Before responding to the browser , Browsers don't know what their real response is . Based on this characteristic , The filter is between Servlet Before , Can intercept the browser to Servlet Request , It can also change Servlet Response to the browser .


Implement and set the filter

stay Servlet/JSP To implement filters in , Must be realized Filter Interface , And use @WebFilter Marked or in web.xml Filter defined in .filter Source code :

public interface Filter {
   
                  
    public void init(FilterConfig filterConfig) throws ServletException;
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
    throws IOException, ServletException;
    public void destroy();
}

You can find that there are three methods to be implemented . Let's talk about these three methods :

  • init: When the filter class is loaded into the container and instantiated , The container will run its init Method and pass in FilterConfig Object as parameter , The role of this object and ServletConfig It's the same thing , Get the filter setting information on behalf of the object .
  • doFilter: The container is calling Servlet Of service Before the method , You can apply a filter , The filter will be called doFilter Method . stay doFilter Methods can be used to service Method preprocessing , Then decide whether to call FilterChain Of doFilter Method . If called FilterChain Of doFilter Method , It will run the next filter , If there is no next filter , Call the target of the request Servlet Of service Method , If you don't call FilterChain Of doFilter Method , Then the request will not be passed on to the next filter or target Servlet, This is it. Intercept request , from Servlet From the point of view of , I don't know that the browser has made a request .
  • If you want to do something before the filter is destroyed , You can define an action to destroy In the method .

We can have a look FilterChain Of doFilter The implementation of the :

Filter filter = filterIterator.next();
if (filter != NULL) {
    filter.doFilter(request, response, this);
} else {
    targetServlet.service(request, response);
}

It is implemented recursively , in other words ,service The subsequent processing of is returned in stack order .

When to trigger the filter , By default, the browser sends out the request directly , If it's those who pass RequestDispatcher Of forward or include Request , Set up @WebFilter Of DispatcherTypes. for example :

@WebFilter(
    filterName = "some",
    urlPattern = {
  
                 "/some"},
    dispatcherTypes = {
        DispatcherType.FORWARD,
        DispatcherType.INCLUDE,
        DispatcherType.REQUEST,
        DispatcherType.ERROR
    }

If you don't set any dispatcherTypes, The default is REQUEST.FORWARD It means passing through RequestDispatcher Of forward And the request can apply Filter , Other concepts are basically similar to this .

If there is one URL or Servlet Multiple filters will be applied , According to web.xml In the order in which they appear , To determine the running order of the filter .

版权声明
本文为[osc_ f9krav3q]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207180526309m.html