The servlet of Java EE

Source: Internet
Author: User

The first thing that can handle a request when learning javaweb, because this thing opens the door to the entire Java EE to create countless possibilities!

The life cycle of the servlet, which defines its life cycle in the Javax.servlet.Servlet interface

1. The client requests the servlet;

2. Load the servlet class into memory;

3. Instantiate and initialize the servlet;

4.init () initialization parameters;

5.service () (Doget () or doPost ());

6.destroy ()

Don't say much nonsense, first get a Hello world.

    1. Create a Dynamic Web project to generate the. xml file

    2. Create a class that inherits HttpServlet ( question 1, why it becomes httpservlet instead of a servlet)

    3. Overwrite the service method of the parent class ( question 2)

The basic architecture is ready.

Import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class HelloServlet Extends HttpServlet {private static final long serialversionuid = 1L; @Overrideprotected void Service (HttpServletRequest R Equest, HttpServletResponse response) throws Servletexception, IOException {String nameStr = request.getparameter ("Name "); System.out.println ("Front-end parameter passed in →name:" +namestr);}}

The following configuration is in Web. xml

<!--Hello--><servlet><servlet-name>/hello</servlet-name><!--resource name-->< servlet-class>cn.peace.servlet.helloservlet</servlet-class><!--resource naming, can be accurately positioned to a servlet to handle-- </servlet><servlet-mapping><servlet-name>/hello</servlet-name><!--exposed to external resource names-- <url-pattern>/*</url-pattern><!--indicate which requests will be intercepted,/* to intercept all--></servlet-mapping><!-- The name value here must be the same--

The process of explaining a request:

Http://localhost:8080/hello?name=%22wow1%22

When requesting the resource Hello, first parse the requested resource name in the URL, here is hello.

Scan Web. XML to find a resource named Hello, and use the class configuration to find the corresponding servlet to process the request.

Question 1: Servlet is an interface, can only be implemented, extremely inconvenient, httpservlet inherit from Genericservlet, and Genericservlet implements the servlet, ServletConfig, Java.io.Serializable these interfaces. This httpservlet is thread-safe.

Question 2: in HttpServlet, there are doget (), DoPost (), service () and other methods, why use service ()?

First, make a note of these methods.

Doget (), handling get requests

DoPost (), processing the POST request

Service (), all requests are dealt with in Httpservlet.class, which is described in the following code

protected void Service (HttpServletRequest req, HttpServletResponse resp)

Throws Servletexception, IOException {


String method = Req.getmethod ();


if (Method.equals (Method_get)) {//Determines whether the request type is GET

Long lastmodified = getlastmodified (req);

if (lastmodified = =-1) {

Servlet doesn ' t support if-modified-since, no reason

To go through further expensive logic

Doget (req, resp);//Call Get method

} else {

Long ifmodifiedsince;

try {

Ifmodifiedsince = Req.getdateheader (header_ifmodsince);

} catch (IllegalArgumentException iae) {

Invalid Date Header-proceed As if none was set

Ifmodifiedsince =-1;

}

if (Ifmodifiedsince < (lastmodified/1000 * 1000)) {

If The servlet mod time is later, call Doget ()

Round down to the nearest second for a proper compare

A Ifmodifiedsince of-1 would always is less

Maybesetlastmodified (resp, lastmodified);

Doget (req, resp);//Call The Post method

} else {

Resp.setstatus (httpservletresponse.sc_not_modified);

}

}


}

This allows you to know that in a servlet, the service method executes first, then the GET or post

In the experiment, the Get or post method is not called if the service method exists

Test code:

Request Url:http://localhost:8080/hello?name=%22wow1%22

Results

Helloservlet.service ()

Front-end parameters passed in →name: "Wow1"

After Servlet 3.0, the annotated version is available

First, the Web. xml file needs to be

<web-app id= "Webapp_9" version= "3.0" xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" Http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_ 3.0.xsd ">

Modify the version= "2.4" to 3.0, and web-app_2.4.xsd to change to 3.0

Just make annotations on the servlet class, for example:

@WebServlet (name= "" urlpatterns= "/hello2")//Urlpatterns need to guarantee unique

PS: Marked red for must have

Case

@WebServlet (urlpatterns= "/hello2")//urlpatterns need to guarantee unique public class Helloservlet2anno extends HttpServlet {private Static final Long serialversionuid = 1L; @Overrideprotected void Service (HttpServletRequest req, HttpServletResponse resp ) throws Servletexception, IOException {System.out.println ("using the annotated version servlet, please wait ....");}

Request Path: Http://localhost:8080/hello2

Results

Using the note version servlet, please wait ....



This article is from the "My Java Road" blog, so be sure to keep this source http://heartofthesea.blog.51cto.com/7651104/1632069

The servlet of Java EE

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.