The base class for servlet, filter, listener inheritance, and how to get scopes

Source: Internet
Author: User

One, servlet:
1. servlet belongs to the Java EE component, and Web project building servlet does not need to import the project framework jar package
2. Servlet Architecture:
In the Java EE API, the supporting interfaces and base classes provided to the servlet are located in Javax.servlet.* and javax.servlet.http.* (providing all APIs related to HTTP requests) in two packages
Interfaces commonly used in servlet packages
Interface ServletConfig
Interface ServletContext
Interface ServletRequest
Interface Servletresponse
Interface Servlet: The methods provided in this interface are Init,getservletconfig,getservletinfo,destroy,service
Jqavax.servlet.Genericservlet (implements the Servlet interface, implements the basic servlet function, provides a service () method)
Javax.servlet.http.HttpServlet (inherits the Genericservlet class, can handle HTTP requests, the provided doget () +dopost () and service () methods work the same

3, implement the Servlet controller function class needs to inherit the HttpServlet class, and override the methods in the HttpServlet class
public class Testservlet extends httpservlet{
public void DoPost (HttpServletRequest req,httpservletresponse resp) throws servletexception,ioexception{
String Username=req.getparameter ("username");//You can call the request and the response method arbitrarily
String name= "admin";
String password= "admin";
System.out.println (name+ "\ t" +password);
}
public void doget (HttpServletRequest req,httpservletresponse resp) throws servletexception,ioexception{
This.dopost (req, resp);
System.out.println ("This is the Get Submit method");
}
With this rewrite, you can avoid the problem of code duplication caused by handling doget or dopost different submissions
or by rewriting the service () method, in fact, overriding the Doget () and Dopost () methods, which are also the programs that automatically call the service () method to parse get or post submissions:
public void Service (HttpServletRequest Req,httpservletresponse resp) throws servletexception,ioexception{
String Username=req.getparameter ("username");//You can call the request and the response method arbitrarily
String name= "admin";
String password= "admin";
System.out.println (name+ "\ t" +password);
}

The life cycle of a servlet: You can understand the life cycle of a servlet by overriding the following two methods (in the filter):
public void init (ServletConfig config) throws servletexception{
When the first request arrives, you can send the initialization configuration of the current servlet to the ServletConfig config type
SYSTEM.OUT.PRINTLN ("servlet initialization");
}
public void Destroy () {------------------------------------->>//server is stopped when loaded, is the last method to call
System.out.println ("Method of destruction of the servlet");
}
4. The servlet obtains the requested object:
Application----ServletContext ServletContext application=config.getservletcontext (), which is obtained through Config, can also be obtained through the session
Session----HttpSession HttpSession session=request.getsession ();
Request---httpservletrequest, all requests that inherit ServletRequest------------>>servlet,filter listener, etc. are of this type
Response---httpservletresponse, inherited servletresponse---------->>servlet,filter Listener All responses are of this type
Config---servletconfig------------------>> get initialization parameter values
Out----Printwriter:printwriter out = Response.getwriter ();
Exception----exception
PageContext----Javax.servlet.jsp.PageContext
Page----Javax.servlet.jsp.JspPage
5. Configuration of servlet in Web. xml:
<!--configuration Servlet--
<servlet>
<servlet-name>LoginServlet</servlet-name>--------->> name defined for this servlet
<servlet-class>net.cstp.servlet.LoginServlet</servlet-class>-------->> let container tomcat load the appropriate servlet class
<1--can set initialization parameters and get that initialization parameter through the ServletConfig config object in the Servlet initialization method--
<init-param>
<param-name>name</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>---------->> in order to find a matching load class (Servlet controller), Same as name in servlet node
<url-pattern>/login</url-pattern>------------------>>servlet Entry, corresponding to the URL of the address bar or the URL of the action in the form, to/ Beginning
</servlet-mapping>

<!--Configure the session lifecycle: minutes-to-
<session-config>
<session-timeout>20</session-timeout>
</session-config>

Second, filter: Filters, Java EE components
1. Filter architecture: In the javax.servlet.* package
Filterconfig: Provides methods for getting application objects Getservletcontext () and methods for initializing request parameters Getinitparameter (String name)
Filterchain: Provides a method for passing requests down Dofilter (ServletRequest request, servletresponse response)
Filter: Provides three methods, filter initializes init (), destroys destroy (), processes request Dofilter (ServletRequest request, servletresponse response, Filterchain chain)
2. How to implement the filter interface function: Implement the filter interface and rewrite the three methods of the filter interface
public class Myfilter implements Filter {
public void init (Filterconfig fconfig) throws Servletexception {
SYSTEM.OUT.PRINTLN ("Filter Initialization succeeded");
}
public void Destroy () {
System.out.println ("Method of Filter Destruction");
}
public void DoFilter (ServletRequest req, Servletresponse resp, Filterchain chain) throws IOException, Servletexception {
Get request requests and response response objects that can handle HTTP requests
HttpServletRequest request= (httpservletrequest) req;
HttpServletResponse response= (httpservletresponse) resp;

    string username= (String) request.getsession (). getattribute ("username");
    if (username!=null) {
     // The variable chain function that invokes the Filterchain interface declaration: 1. Let the request pass down the filter; 2. Function of splitting: processing request, processing response
      SYSTEM.OUT.PRINTLN ("Related requests for processing");
     chain.dofilter (request, response);
     system.out.println ("Processing related responses");
    }else{
     response.sendredirect (".. /index.jsp ");
    } 
   }

}
3. Filter configuration in Web. xml:
<!--all Filters--
<filter>
<filter-name>YourFilter</filter-name>
<filter-class>net.cstp.filter.YourFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>YourFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--selective filtering--
<filter-mapping>
<filter-name>YourFilter</filter-name>
<url-pattern>/update</url-pattern>
</filter-mapping>

Third, Listener: Listener, Java EE components
1, listener architecture, located in Javax.servlet.* and javax.servlet.http.*: for different scope objects, to provide the corresponding implementation interface, and depending on the role of different functions to distinguish the implementation of the interface
Request object:
Interface Servletrequestlistener: Provides methods for creating and destroying
Interface Servletrequestattributelistener: Monitoring of the addition, deletion, substitution of property values in the scope
Session object:
Interface Httpsessionlistener, which can be used to count the current number of online people on the website
Interface Httpsessionattributelistener: Binding value unbound
Interface Httpsessionbindinglistener
Application object:
Interface Servletcontextlistener: Monitor tomcat startup or destruction, or it can be used to count website history visits when Web projects are loaded or destroyed
Interface Servletcontextattributelistener
2. Custom Listener:
1), implement Servletrequestlistener interface:
public class Validaterequestlistener implements Servletrequestlistener {
public void requestdestroyed (Servletrequestevent event) {
SYSTEM.OUT.PRINTLN ("The listener has been destroyed");
}
public void requestinitialized (Servletrequestevent event) {
SYSTEM.OUT.PRINTLN ("Listener has been started");
ServletRequest req=event.getservletrequest ();
HttpServletRequest request= (httpservletrequest) req;
....
}
}
2), implement Servletrequestattributelistener interface:
public class Validateservletarributerequest implements Servletrequestattributelistener {
When the value is added to the scope, it can be monitored
public void attributeadded (Servletrequestattributeevent arg0) {
System.out.println ("Add a property name to the request Scope" +arg0.getname () + "has the value:" +arg0.getvalue ());
}
When the value is removed from the scope, it can be monitored
public void attributeremoved (Servletrequestattributeevent arg0) {
System.out.println ("Removed value from Scope" +arg0.getname () + "value is:" +arg0.getvalue ());
}
When the values in the scope are replaced, they can be monitored
public void attributereplaced (Servletrequestattributeevent arg0) {
System.out.println ("Get substituted value:" +arg0.getname () + "value is:" +arg0.getvalue ());

ServletRequest req=arg0.getservletrequest ();
HttpServletRequest request= (httpservletrequest) req;
String Name= (String) request.getattribute ("name");
System.out.println ("The value after obtaining the replacement is:" +name);
}
}
3. Configuration of Listener in Web. XML: Which to use, which to add
<listener>
<listener-class>net.cstp.listener.ValidateRequestListener</listener-class>
</listener>

<listener>
<listener-class>net.cstp.listener.ValidateSessionListener</listener-class>
</listener>
<!--
<listener>
<listener-class>net.cstp.listener.ValidateApplicationListener</listener-class>
</listener>
Iv. Configuration order and loading order of servlet, filter, listener:
The order of loading is independent of their sequencing in the Web. xml file. That is, the filter is not loaded before the filter is written in front of the listener. But the order of configuration is consistent with the loading order and is easy to manage
The order in which Web. XML is loaded is: Context-param, listener, filter, and servlet, while the order of actual program calls between the same types is called according to the Order of the corresponding mapping.

The base class for servlet, filter, listener inheritance, and how to get scopes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.