How to add a web framework in Servlet

Source: Internet
Author: User

Init () method

The init method is loaded in the container.Servlet,ServletThe container only calls the init method once after instantiation. The init method must beServletCompleted before receiving any request.

This method is usually used to manage and initialize some resources, such as reading configuration data from the configuration file, reading initialization parameters, and initializing delayed buffering.

GetservletConfig () method

The GetservletConfig method returns a servletConfig object, which is used to return thisServletThe initialization information and startup parameters. The returned result is passed to the init method servletConfig.

Service () method

The Service method is the entry point of the application logic.ServletThe core of the method is that the WEB Container calls this method to respond to incoming requests. OnlyServletAfter the init () method is initialized, the Service method is called.

GetservletInfo () method

This method returns a String object.ServletInformation, such as the author and version.

Destroy () method

The destroy method is removed from the container.Servlet. This method will be executed after the service () method of all threads is completed or times out. After this method is called, the container will not call this method againServletThat is, the container no longer sends the request to thisServlet. This method isServletThe opportunity to release the occupied resources is usually used to execute some cleanup tasks.

This interface defines the initialization ofServlet, Service request and remove from ContainerServlet. They are executed in the following order:

◆ServletAfter being instantiated, use the init Method for initialization.

◆ Any client request calls the service method

◆ServletThe removed service is destroyed by calling the destroy method.

ServletSuch:

Request Distribution

Request distribution allowsServletThe RequestDispatcher interface provides a mechanism for allocating requests to another resource. You can obtain an object that implements the RequestDispatcher interface from servletContext in the following two ways:

◆ GetRequestDispatcher

◆ GetNamedDispatcher

The getRequestDispatcher method accepts a URL path pointing to the target resource.

RequestDispatcher rd = getservletContext (). getRequestDispatcher ("/catalog ");

The getNamedDispatcher method accepts oneServletName parameter, which is in the deployment descriptor <Servlet-Name> the name specified by the element.

RequestDispatcher rd = getservletContext (). getNamedDispatcher ("catalog ");

The RequestDispatcher interface has two methods, allowing youServletAfter completing the preliminary processing, allocate the request response to another resource,

Forward () method:

Public void forward (servletRequest request, servletReponse reponse) throws SwerletException, IOException

Forward the request to anotherServletOr jsp, html, and other resources. The resource is responsible for the response. For example:

 
 
  1. RequestDispatcher rd = getservletContext().getRequestDispatcher(“/catalog”);  
  2. rd. forward(request,response); 

Include () method:

Public void include (servletRequest request, servletReponse reponse) throws SwerletException, IOException
Include method to make yourServletThe response contains the content generated by another resource.

 
 
  1. RequestDispatcher rd = getservletContext().getRequestDispatcher(“/catalog”);  
  2. rd. include(request,response); 

IntegrationWebWorkSpecific analysis

WebWorkIs a J2EE Web Framework developed and implemented by OpenSymphony. After the introductionServletFor more information, seeWebWorkHow to injectServletSuppose we have a WEB application whose context is "/WebWorkdDemo.

Deployment descriptor

In the deployment descriptor, We need to configure the following:

 
 
  1. ﹤servlet﹥  
  2. ﹤servlet-name﹥webwork﹤/servlet-name﹥  
  3. ﹤servlet-class﹥com.opensymphony.webwork.dispatcher.servletDispatcher﹤/servlet-class﹥  
  4. ﹤/servlet﹥  
  5. ……  
  6. ﹤servlet-mapping﹥  
  7. ﹤servlet-name﹥webwork﹤/servlet-name﹥  
  8. ﹤url-pattern﹥*.action﹤/url-pattern﹥  
  9. ﹤/servlet-mapping﹥  

We declareWebworkOfServletAnd *. action to thisServletIng, thisServletYesWebworkController in the MVC framework.

Map requestsServletThe XWork configuration file xwork. xml contains the following fragments:

 
 
  1. ﹤action name="demo" class=" webworkapp.DemoAction"﹥  
  2.        ﹤result name="success" type="dispatcher"﹥  
  3.               ﹤param name="location"﹥/demo.jsp﹤/param﹥  
  4.        ﹤/result﹥  
  5. ﹤/action﹥  

In this case, we use http: // localhost: 8080/WebWorkDemo/demo. when the URL action sends a request to the server, the WEB Container first determines which WEB application to transfer, after the container matches the request URL with the context, it knows that it will go to the/WebWorkdDemo WEB application.

Then, the container searches for the deployment descriptor of the/WebWorkdDemo application to process the request.ServletAccording to the suffix *. action, find the nameWebworkThisServletIn this way, the request is mappedWebworkCom. opensymphony.Webwork. Dispatcher. servletDispatcher. This is the Controller componentServletIn the service () method, the corresponding action is parsed Based on the Request Path for processing.

Through the above processing, the web request is transferredWebworkThe Controller servletDispatcher in. Not onlyWebworkThe MVC web framework requires similar processing to transfer web requests to its controller for further processing.

ServletLife Cycle

ServletDispatcherServletThe storage cycle can be as follows:

When the server is started, the container first instantiates servletDispatcher.

After instantiation, The init () method is called and the following operations are performed in the init method:

◆ Initialize the Velocity Engine

◆ Check whether the Configuration File Reload function is supported. If yes, each request will reload the xwork. xml configuration file, which is very convenient during development.

◆ Set some file upload information, such as uploading temporary directories and uploading maximum bytes.

Every request calls the service) method. The following methods are executed in the service method:

◆ Get the action namespace through the request

◆ AccordingServletThe Request Path to parse the name of the Action to call the request actionName)

◆ Create Action context extraContext), traverse the data in HttpservletRequest, HttpSession, and servletContext, and copy itWebworkSo far, all data operations are performed in this Map structure, so that the internal structure andServletAPI phase separation.

◆ As a parameter, call ActionProxyFactory to create the corresponding ActionProxy instance. ActionProxyFactory creates an ActionProxy instance according to the settings in the Xwork configuration file xwork. xml. ActionProxy contains the Action configuration information, including the Action name and implementation class ).

◆ Execute () method of proxy
Container RemovalServletRun destroy ().ServletThe destroy method is not overwritten.ServletWill do nothing.

Request Distribution

WebWorkMultiple live and flexible view display modes are provided. For example, we still use the above configuration in xwork. xml:

 
 
  1. ﹤action name="demo" class=" webworkapp.DemoAction"﹥  
  2.        ﹤result name="success" type="dispatcher"﹥  
  3.               ﹤param name="location"﹥/demo.jsp﹤/param﹥  
  4.        ﹤/result﹥  
  5. ﹤/action﹥  

According to the above configuration, when the return value of DemoAction is "success", the processing type is "dispatcher". When the result type is "dispatcher", the javax.ServletThe. RequestDispatcher's forward () or include () method combines the processing result with the presentation layer and then presents it to the user.
Let's take a look.WebWorkCom. opensymphony.WebworkCode snippet in. dispatcher. servletDispatcherResult:

 
 
  1. HttpservletRequest request = servletActionContext.getRequest();  
  2.  HttpservletResponse response = servletActionContext.getResponse();  
  3.  RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);  
  4.  if (dispatcher == null) {  
  5.    response.sendError(404, "result '" + finalLocation + "' not found");     
  6.    return;  
  7.  }  
  8.  if (!response.isCommitted() && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {  
  9.    request.setAttribute("webwork.view_uri", finalLocation);  
  10.    request.setAttribute("webwork.request_uri", request.getRequestURI());  
  11.      
  12.    dispatcher.forward(request, response);  
  13.  } else {  
  14.    dispatcher.include(request, response);  
  15.  }  


The servletDispatcherResult class obtains HttpservletRequest and HttpservletResponse from servletActionContex, and then calls request. getRequestDispatcher (finalLocation) method to get a RequestDispatcher instance. If the returned value is null, an error not found on the 404 page is output. Otherwise, the dispatcher is called. forward (request, response) or dispatcher. include (request, response) is used to distribute requests, and the processing result and presentation layer are merged and presented to users.

Conclusion

How to add a web framework in ServletServletHave a simple understanding, if you want to study more, you can readServletSpecifications and the source code of some mature frameworks.

  1. What are servlets and common Servlet APIs?
  2. At the beginning of JSP Servlet Development
  3. Java Servlet API documentation
  4. Integrate JSP and PHP in Apache
  5. Java Servlets (JSP) Development Environment

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.