First, what is a servlet
The servlet is the first Web Component model proposed by Java EE. A servlet can only be run in a Java EE Web container.
Second, servlet work flow
1. Initialization
Each servlet corresponds to a URL address. When the Web container accepts request information for a URL address, the request is forwarded to the specified servlet for processing based on the mapping between the URL address and the servlet. If an instance of this servlet does not exist in the Web container, the Web container dynamically loads and instantiates the servlet.
2. Request Processing
For client requests, the Web container will generate a new thread to invoke the servlet's service () method. The service () method examines the HTTP request type (Get\post\put\delete, etc.), and then calls the appropriate doget () \dopost () \doput () \dodelete () method. The most common type of request is get and post. The difference is that if transferred as a GET request, the request parameters are attached directly to the requested URL, and if transmitted as a POST request, the parameters are packaged in the packet and sent to the server.
Note: A servlet has only one instance at a time, and it is retained for the duration of the servlet's use. When multiple requests are sent to the same servlet, the server creates a new thread for each request to process the client's request.
3. Exit
When the client request is processed, the instance of the servlet is not immediately destroyed by the Web container. The Web container removes the servlet vision from memory only if the Web application is closed or the servlet has been idle for a long time. The Destroy () method of the servlet is called by the Web container before removal.
The servlet can use this method to close the database connection, interrupt the background thread, write a cookie list to the disk, and perform other cleanup actions. Note: If the Web container is shut down unexpectedly, the Destroy () method cannot be guaranteed to be called.
As can be seen from the servlet workflow above, the client and servlet do not interact directly, regardless of whether the client's request to the servlet or the servlet's corresponding to the client is implemented through a web container, ensuring the portability of the servlet components.
The responsibilities of the Web container are summarized as:
- Manage the life cycle of servlet components, and be responsible for initialization and destruction of servlet assembly;
- Maps the request to the corresponding servlet and returns the resulting response to the specified client.
The servlet workflow fully embodies the core programming idea of Java EE "component-container".
Third, Servlet API
- HttpServlet: A Web-based servlet component typically inherits this interface to complete processing of client requests.
- HttpServletRequest: Represents the request sent to the servlet component.
- HttpServletResponse: Represents the response from the servlet component returned to the client.
- HttpSession: Represents the space that is used to hold specific client state information during a web app run.
- ServletContext: Represents the runtime environment information for a servlet component.
- ServletConfig: Represents the configuration information for the servlet component.
- Servletexception: Represents an unexpected object that is thrown during the operation of a servlet component.
- RequestDispatcher: Request forwarder, you can forward a client request from one servlet to another server resource such as other servlet, static HTML page, etc.
Iv. the first servlet
To write a servlet component:
- Create a class that implements the Javax.servlet.http.HttpServlet interface.
- Override the Doget () or Dopost () method to implement a dynamic response to HTTP request information.
Since the Java EE5 specification, annotations can be used instead of complex configuration files.
Here's an example:
@WebServlet ("/servlet-first") public class Servlet extends HttpServlet {private Static final Long serialversionuid = 1l;protected void ProcessRequest (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {response.setcontenttype ("text/html;charest=utf-8"); PrintWriter out = Response.getwriter (); Out.println ("
Run Tomcat and the browser opens input "Http://localhost:8080/ServletDemo/servlet-first".
Note: Define an annotation @webservlet before the class that contains two properties name and Urlpattern, respectively, to define the name and URL pattern of the servlet component. When this component is deployed, the Web container automatically completes the deployment configuration for this servlet component based on this annotation. To use annotation @webservlet, reference javax.servlet.annotation.WebServlet is required.
V. Processing of requests
Here's an example:
<! DOCTYPE html>
@WebServlet ("/getinf") public class Getinf extends HttpServlet {private static final long serialversionuid = 1L; protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("UTF-8"); PrintWriter out = Response.getwriter (); try {String name = Request.getparameter ("name"); String age = Request.getparameter ("Age"); String datestring = request.getparameter ("Birthday"); SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd"); Java.util.Date birth = Format.parse (datestring); string[] paravalues = request.getparametervalues ("CheckBox1"); String hobbies = new String (""); for (int i = 0; i<paravalues.length;i++) {Hobbies + = paravalues[i]+ "";} Out.println ("Vi. Filtering requests using filter
In addition to using the Servlet component to process client requests directly, Java EE provides a component to filter processing of request information, called filter. Unlike a servlet, he cannot generate a response to the client, but filter can intercept requests and responses in order to view, extract, or somehow manipulate the data being exchanged between the client and the server. Filter can change a request or modify a response. The Association of the filter with the servlet is defined by the Web app's configuration file or annotations.
When a user sends a request to a servlet, the servlet is executed first because of the filter associated with the servlet before the servlet processes the request. If a servlet has multiple filter, it is executed according to the order of the configuration.
Filter is used primarily for the following scenarios:
- Verify identity when accessing a specific resource (web, JSP, servlet).
- Access records tracking for a resource.
- Accesses the transformation of a resource.
A filter must implement the Javax.servlet.Filter interface, that is, implementing the following three methods:
- DoFilter (ServletRequest request, servletresponse response, Filterchain chain). The method used to implement the filtering behavior. The Filterchain object introduced provides the information to be called by subsequent filter.
- Init (Filterconfig fconfig). The filter apprenticeship method that is called by the container.
- Destroy ().
Here's an example:
@WebFilter (filtername= "/ipfilter", urlpatterns={"/*"}) public class IPFilter implements Filter {private filterconfig Fconfig = Null;public void Destroy () {this.fconfig = null;} public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {String ipAddress = request.getremoteaddr (); System.out.println ("IP" + ipAddress + ", time" + New Date (). toString ()); Chain.dofilter (request, response);} public void init (Filterconfig fconfig) throws Servletexception {This.fconfig = Fconfig;}}
Note:
There are two mapping modes of filters:
- The mapping of the URL pattern, which is also the default mapping mode. You can try wildcard characters, such as "/*" in URL mode.
- The mapping to the servlet. At this point the filter is associated with the servlet's logical name.
As with the servlet, the new version of the Java EE Specification provides annotation @webfilter to deploy the filter component whose properties are filtername to the logical name of the filter and urlpatterns to the URL pattern of the filter.
The program contains three interface methods that the filter must implement: Init (), Destroy (), and Dofilter (). The init () method is called when the container loads the filter for the first time. The class This method contains a reference to the Filterconfig object. The filtering function for requests and responses is primarily implemented by Dofilter (). The Web container calls the Destroy () method before garbage collection so that it can execute any code that must be cleaned.
Java--servlet