"Graphic" Javaweb:servlet tutorial

Source: Internet
Author: User
Tags abstract class definition ftp file http post http request print object tomcat tomcat server

One, Web server

The person who is engaged in the web development, will be very clear a thing call a Web server, like Java EE develops-tomcat,jetty,. NET development-iis and so on. HTTP servers use HTTP (Hypertext Transfer Protocol) to exchange information with the client browser. Here is the HTTP server simple interaction diagram:

HTTP server is a Web server is one of the most common development, there are other ways of information interaction, such as FTP file server ...

A Web server is a program that can provide documents to the requesting browser. Its core process is

Connection procedure-Request process-answer process-close connection

This reminds me of a picture of the Tomcat architecture:



Two, Tomcat simple say a few words

As pictured, Tomcat includes the core service modules: The connector connection module and the Container container. The Tomcat Server core is a servlet/jsp Container. For each HTTP request, the procedure is as follows

-Get connections
-servlet to analyze requests (httpservletrequest)
-Invokes its service method for business processing
-produces the corresponding response (HttpServletResponse)
-Close Connection

As shown in figure:

The Blue line pointing process is a request, and the Green Line pointing process is the response process. The Web Server Core process above: "Connection procedure-Request process-answer process-close connection"


third, my first servlet

What is a servlet? (Every time you keep asking yourself, what is this "What"?) followed by what should be the "how" it?

In the Java EE 6 documentation, the following are described

The Servlet is a Java applet that runs on the Web server. The servlet can obtain and respond to requests made by Web clients. In general, transmission communication is carried out via HTTP, the Hypertext Transfer Protocol. ”

A servlet is a small Java programming that runs within a WEB server. Servlets receive and respond to requests from WEB clients, usually across HTTP, the hypertext Transfer.

Therefore, the Servlet is an abstraction of the core work of the Web server. It is not just the realization of httpservlet, may be achieved ftpservlet (this I guess) and so on. Relatively more web development, it must be known that the HttpServlet.

Added, as the servlet specification reads:

Serlvet is a Java-technology-based Web Component, hosted by the container, for the production of dynamic content. It is also a platform-independent Java class format that is compiled into platform-independent bytecode and can be dynamically loaded and run by a Java technology-based Web server. Here the container, sometimes called the servlet engine.

In the Java EE 6 documentation, this is how HttpServlet is described:

"HttpServlet provides an abstract class that can be inherited to create an HTTP servlet that adapts to Web sites. ”

Provides an abstract class to is subclassed to create an HTTP servlet suitable for a Web site.

Speak not practice false, practice a "hello,servlet/jsp world!":

import java.io.ioexception;
import java.io.printwriter;
  import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse; /*  * copyright [2015] [jeff lee]  *  * licensed under the
 Apache License, Version 2.0  (the  "License");  * you may not use this file except in compliance with
 the license.  * you may obtain a copy of the license at  *  *    http://www.apache.org/licenses/license-2.0  *  * unless required by  applicable law or agreed to in writing, software  *  distributed under the license is distributed on an  "As is"  basis,  * without warranties or
 conditions of any kind, either express or implied.  * See the License for the specific language governing 
Permissions and  * limitations under the license.  */ /**  *  @author  jeff lee  *  @since  2015-6-25 19:46:45   *  hellowrold case  */@WebServlet (urlpatterns =  "/helloworld.html") public class  helloworldservlett extends httpservlet{          
private static final long serialversionuid = 1l;        @Override     protected void doget ( HTTPSERVLETREQUEST REQ, HTTPSERVLETRESPONSE RESP)       &Nbsp;     throws servletexception, ioexception{         //  Get output Print object         printwriter out
 = resp.getwriter ();
        out.println ("hello,servlet/jsp world!");    &NBSP}}


Right-click the Helloworldservlett.java file-run as-run on server-select Tomcat Server-finish


Wait a moment and you can see the output on the page as follows. This is the response that the client obtains from the HttpServlet:

Third, the analysis of the source

@WebServlet (urlpatterns = "/helloworld.html")

@WebServlet annotations are used to declare a httpservlet configuration. wherein, Urlpatters = "/helloworld.html", urlpatterns plural form, stating that at least one URL must be declared. It and another value must exist one, but cannot exist at the same time. If you want to match multiple URL paths, the following are:

@WebServlet (Urlpatterns = {"/helloworld01.html", "/helloworld02.html"}

Here's a @override that overrides the Doget method of the parent class HttpServlet. Let's look at the httpservlet of the parent class first. HttpServlet is an abstract class that provides the following methods:

-doget, service to HTPP GET request
-dopost, service to HTTP POST requests
-doput, service to HTTP put request
-dodelete, service to HTTP DELETE request
...

As shown in figure:

For different requests, the HttpServlet subclass must implement at least one method, usually one of them, so that the code is more clear. What about the Doget method of the parent class?

protected void doget (httpservletrequest req,  HTTPSERVLETRESPONSE RESP)         throws servletexception,  ioexception     {        string protocol
 = req.getprotocol ();         string msg = lstrings.getstring ("Http.method_
Get_not_supported ");         if  (Protocol.endswith ("1.1"))  {             resp.senderror (httpservletresponse.sc_method_not_allowed
,  msg);         } else {       
     resp.senderror (HTTPSERVLETRESPONSE.SC_BAD_REQUEST, MSG);        &NBSP}     } 


Here is a simple acquisition of the next HTTP protocol and HTTP local information, and then can be the protocol is 1.1, to make a 405 or 400HTTP status code response.

Back to Helloworldservlett.java here:

@Override
protected void doget (HttpServletRequest req, HttpServletResponse resp)
throws Servletexception,    IOException {
//Get Output Print object
printwriter out = Resp.getwriter ();
Out.println ("hello,servlet/jsp world!");
}


Indicates that the Helloworldservlett will accept the HTTP GET request and Oom to HttpServletRequest and execute the logic code inside and return the response. This obtains the output print object PrintWriter from the HttpServletResponse object, and then outputs the "hello,servlet/jsp world!".

Complete! Oh, there's one more thing. Supplementary supplementary:

Print, it's okay to say a word here. If printing a table would be cumbersome, there is a JSP thing that appears and is the HTML avatar of the servlet.

V. In-depth servlet specific process

And back to this simple get servlet code:

public class helloworldservlett extends httpservlet{           private static final long 
serialversionuid = 1l;        @Override     protected void doget ( HTTPSERVLETREQUEST REQ, HTTPSERVLETRESPONSE RESP)              throws servletexception, ioexception{         //  Get output Print object         printwriter out =
 resp.getwriter ();
        out.println ("hello,servlet/jsp world!");    &NBSP}} 


The process is summarized as follows:

-Get the connection "/helloworld.html" from the browser (Client)
The-TOMCAT Connector module passes requests (request) to the container module
-container module will do the following things
--Analyze HTPP request information and assemble it into HttpServletRequest object
--Create a new HttpServletResponse object
--Search the appropriate servlet based on the routing configuration, and create a thread to handle this request. At this point, the thread passes the index of the above request and response objects to the servlet

-Servlet processing logic in new threads

-After the thread is finished, return the browser with a message via the printwriter of the HttpServletResponse object

The process diagram is as follows:


The Blue line pointing process is a request, the Green line pointing process is the response process, the Orange Line pointing process is the internal processing process.

Some questions will ask:

is the servlet thread-safe?

No, a servlet implementation class will have only one instance object, and multiple threads may access the same Servlet instance object, and thread safety issues are caused by global variables and static variables.

Therefore, the Servlet object instantiation is when the servlet is requested for the first time, and if it is accessed, the instance object exists in memory, and it disappears only when the server stops. It does not end with each thread ending. So the next time you visit the servlet, the servlet container searches for the appropriate servlet, and if it does not, container create the corresponding servlet. This is the result we want.

One more disgusting interview question:

Is the servlet a single case?

Not necessarily, in a serveltname case yes. When multiple servletname are matched to a servlet class, the servlet is not a single instance.

Vi. Summary

Find this blog write too much, look back. It can be written in three articles. The main points of this article are as follows

1. Brief introduction of Web server and Tomcat container
2, the first Sevlet development and use
3, in-depth source code and API introduction use
4. Summarize the real process of request and response



Javaweb:servlet Continuation

first, return to the HttpServlet service method

The Servlet base interface defines the service method that is used for client request processing. When the request arrives in the servlet container, it is routed to a servlet instance by the servlet container.

For example, the Javax.servlet.http.HttpServlet class, which has a protected void service method, is as follows:

private static final string method_delete =  "DELETE";
private static final string method_head =  "Head";
private static final string method_get =  "Get";
private static final string method_options =  "Options";
private static final string method_post =  "POST";
private static final string method_put =  "put";
private static final string method_trace =  "TRACE";
  private static final string header_ifmodsince =  "If-Modified-Since";   private static final string lstring_file =       
   "Javax.servlet.http.LocalStrings"; private static resourcebundle lstrings =         
Resourcebundle.getbundle (Lstring_file); /**  * htTP Status Code 304  */public static final int sc_not_modified = 304;
 /**  *  receives standard HTTP requests from the  public service method,  *  and distribute them to the Doxxx method defined in this class.
 */Protected void service (HTTPSERVLETREQUEST REQ, HTTPSERVLETRESPONSE RESP)         throws servletexception, ioexception { 
   //  Get Request Method name     string method = req.getmethod ();
    //  if it is GET request     if  (Method.equals (method_get))  {         //  the last time you modified the HttpServletRequest object     
    long lastmodified = getlastmodified (req);         //  did not change         if   (lastmodified == -1)  {            doget (REQ, RESP);         } else {       
     long ifModifiedSince;             try {                 //  Get server modification time in request header                  ifmodifiedsince =
 req.getdateheader (header_ifmodsince);             } catch  ( Illegalargumentexception iae)  {                 //  Get Invalid            
     ifModifiedSince = -1;             }             / /  if the request header server is modified late             if  ( ifmodifiedsince <  (lastmodified / 1000 * 1000))  {                 //  Set the time to modify the HttpServletResponse object, and reset the browser's parameters                               
 //maybesetlastmodified (resp, lastmodified);                 //  Call Doget Method                                  doget (req,  resp);             } else {                 // 304 http Status Code                  resp.setstatus (SC_
not_modified);             }        &NBSP;&NBSP}     } else if  (Method.equals (method_head))  {  
      long lastmodified = getlastmodified (req);
      //maybesetlastmodified (resp, lastmodified);
        dohead (REQ,&NBSP;RESP);     } else if  (Method.equals (method_post))  {    
    dopost (REQ,&NBSP;RESP);     } else if  (Method.equals (method_put))  {        doput (
REQ,&NBSP;RESP);     } else if  (Method.equals (method_delete))  {    
    dodelete (REQ,&NBSP;RESP);     } else if  (Method.equals (method_options))  {   
     dooptions (REQ,RESP);     } else if  (Method.equals (method_trace))  {    
    dotrace (REQ,RESP);
    } else {        //  if not asked to         string errmsg = lstrings.getstring ("Http.method
_not_implemented ");
        Object[] errArgs = new Object[1];         errargs[0] = method;
        errmsg = messageformat.format (ErrMsg, errArgs);         // 501 http Status Code       
  resp.senderror (HTTPSERVLETRESPONSE.SC_NOT_IMPLEMENTED,&NBSP;ERRMSG); &NBSP;&NBSP;&NBSP;&NBSP}}

The


code logic is detailed as follows:

1, HttpServlet's protected void service method is used to accept standard HTTP requests received by the public service.

In other words, HttpServlet overrides the service method of the parent class Genericservlet. As the figure shows, the ServletRequest and Servletresponse objects obtained from the container are coerced into the HttpServletRequest and HttpServletResponse objects for HTTP processing. Two objects are then routed to the HttpServlet protected Void service method (code selected in the figure)


2, and then distributes to the Doxxx method of this class definition according to the requested method name. Returns the 501 HTTP status code if it is not requested.

This seems to understand what, that is, if you rewrite the Doget method in HelloServlet, this is distributed to the Doget method of HttpServlet subclass HelloServlet.

Oh also, 501 HTTP status code-not implemented (not implemented) indicates that the server does not support the functionality required to implement the request. For example, the customer issued a put request that the server does not support. So, what is the use of rote memorization of these HTTP status codes? Such a memory is the most effective.

    Rest, small ads inserted: (Maintenance, O (∩_∩) o~)

    The code involved will be in the open source project Servlet-core-learning. The example of-servlet/jsp learning accumulation is the best practice for Java EE Beginners and servlet/jsp core technology consolidation

which is roughly the two steps. This is the service workflow:

    1, a standard HTTP request received by the public service.

    2, distribution to defined Doxxx method

Second, GET request processing details

The above processing for GET request code is as follows:
   

  If it is GET request if  (Method.equals (method_get))  {    // 
The time of the last modification of the HttpServletRequest object     long lastmodified = getlastmodified (req);
    //  no change     if  (lastmodified == -1)  {
        doget (REQ,&NBSP;RESP);     } else {        long 
Ifmodifiedsince;         try {             //  Get server modification time in request header           
  ifmodifiedsince = req.getdateheader (header_ifmodsince);
        } catch  (illegalargumentexception iae)  {             //  Get Invalid &NBSP;&NBSP;&NBSP;         ifmodifiedsince = -1;         }         //  If the request header server was modified late         if  (ifmodifiedsince <  ( lastmodified / 1000 * 1000)  {             //  set the time to modify the HttpServletResponse object, reset the browser's parameters        
   //maybesetlastmodified (resp, lastmodified);             //  calling Doget method    
         doget (REQ,&NBSP;RESP);         } else {             // 304 http Status Code             &nbsP;resp.setstatus (sc_not_modified);         }    &nbsp}}


Over here

1, defines the getlastmodified (req) method. Used to get the time when the HttpServletRequest object was last modified. If LastModified is the default 1L, it is always refreshed.

This getlastmodified is httpservlet defined to support conditional get operations. That is, when a client obtains a resource through a GET request, the data is used again when the resource has changed since the first time the actual point has been fetched, or the client-cached data is applied.

In some suitable situations, the implementation of this method can be more efficient use of network resources, reduce unnecessary data transmission.

2, if the return value of the Getlastmodified method is a positive number, it should be divided into the following two scenarios:

(1) If the request header does not contain the If-modified-since header field (which should be the first time the resource is accessed) or its getlastmodified return value is newer than the If-modified-since header field, then the call Doget returns the generated Response and sets the last-modified message header.

(2) if its getlastmodified return value is older than the If-modified-since header field specified, returns a 304 status to the client, indicating that the client continues to use the previously cached page.

For example, 304, the first visit to Baidu home, some resources will be successful to return 200. F5 again, some resources or the cached data that invokes the client directly, returns 304.




Third, servlet threading issues

The servlet container can concurrently route multiple service methods that request to the servlet. To handle these requests, the servlet must handle concurrency and thread-safety issues. The previous "servlet must Know" mentions that defining global variables can cause thread-safety problems. When developing a servlet, consider threading security issues to address:

1. Implement Singlethreadmodel interface

Servlet2.4 has proposed not to promote use. Implementing this interface, the servlet container creates a separate servlet instance for each new request. This can have serious performance problems.

2. Synchronous lock

Using the Synchronized keyword, although it is guaranteed that only one thread can access the protected section, it is guaranteed to be thread safe. But the system performance and the concurrent quantity greatly reduces. Not to take ~

3, avoid the use of instance variables, that is, the global variables in the servlet. Use local variables (recommended)

The local variables in the method are allocated in the stack space, and each line Chengyu the private stack space. Therefore, access is thread-safe.

I thought of one of the following:

Since Sevlet's global variable is thread-unsafe, so does SPRINGMVC Controller. Does it make thread-safe for us to define a Xxxservice variable in controller?


A: Because this is a service Bean for spring, it is thread-safe, so it can be used as a single case without causing thread safety.

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.