A brief analysis of Serlvet3.0 annotation _servlet

Source: Internet
Author: User
(1) Note configuration One, Servlet3.0 introduction

SERVLET3.0 is part of the Java EE6 Specification, Servlet3.0 provides annotations (annotation), making it no longer necessary to perform a servlet deployment description in a Web.xml file to simplify the development process. Ii. the required environment for the development of Servlet3.0 procedures

The development of Servlet3.0 programs requires a certain amount of environmental support. Both MYECLIPSE10 and TOMCAT7 provide support for the Java EE6 specification. Need to manually configure the environment if you are using a low version
Therefore, the development of the SERVLET3.0 program requires the following development environment support:
-Ide:myeclipse 10+
-Jdk:jdk 1.6+
-Tomcat:tomcat 7+

Import java.io.IOException;  
Import javax.servlet.ServletException;  
Import Javax.servlet.annotation.WebServlet;  
Import Javax.servlet.http.HttpServlet;  
Import Javax.servlet.http.HttpServletRequest;  

Import Javax.servlet.http.HttpServletResponse; /** * Annotation Webservlet is used to describe a servlet * attribute name that describes the name of the servlet, Optional * attribute urlpatterns define the URL to access, or use property value to define the URL to access. (Definition access URL is required attribute) *//Note configuration @WebServlet (displayName = "Userservlet",//Description name = "Userservlet",//servlet name URLP  
Atterns = {"/user"},//url Loadonstartup = 1,//Startup Item InitParams = {@WebInitParam (name = "Username", value = "John")} //Initialization parameters */@WebServlet (name= "Servlet3demo", urlpatterns= "/servlet3demo") public class Servlet3demo extends Httpse Rvlet {public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexc  
    Eption, IOException {response.getwriter (). Write ("Hello Servlet3.0"); } public void DoPost (HttpServletRequest request, HttpSErvletresponse response) throws Servletexception, IOException {this.doget (request, response);  
  } * * completed a servlet program development using the annotation description.  
  Use @webservlet to define a class that inherits from Javax.servlet.http.HttpServlet as a servlet component.  
      @WebServlet has many properties: 1, asyncsupported: Declares whether the servlet supports asynchronous operation mode.  
      2, the description of Description:servlet.  
      3, the Displayname:servlet display name.  
      4, Initparams:servlet init parameter.  
      5, the name of the Name:servlet.  
      6, the Urlpatterns:servlet access URL.  
  7, the Value:servlet access URL.  
  The access URL of the servlet is a required attribute of the servlet, optionally using the Urlpatterns or value definition.  
  Like the above Servlet3demo can be described as @webservlet (name= "Servlet3demo", value= "/servlet3demo"). Multiple URL accesses are also defined: such as @webservlet (name= "Servlet3demo", urlpatterns={"/servlet3demo", "/servlet3demo2"}), or @webservlet (name=   "Annotationservlet", value={"/servlet3demo", "/servlet3demo2"}) * * *
Note The version information in the Web.xml file, version= "3.0" and http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd This means that you are currently using Servlet3.0 versions. (2) Asynchronous invocation

In Servlet3.0, asynchronous processing is supported within the servlet. Its logic is that when we request a servlet, our servlet can return a portion of the content to the client first. The other logic is then processed asynchronously within the servlet, and the result of the asynchronous processing is returned to the client after the asynchronous process completes.
Note: Asynchronous processing of time-consuming business

@WebServlet (value= "/s3", asyncsupported=true) public class Servlet3 extends httpservlet{@Override public void Ser
        Vice (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//Requests
        Request.setcharacterencoding ("Utf-8");
        Response Response.setcontenttype ("Text/html;charset=utf-8");
        Final PrintWriter out=response.getwriter (); Out.println ("<p> the content that is output before asynchrony.)  
        </p> ");  

        Out.flush ();  
          Begins an asynchronous call to get the corresponding asynccontext.  
          Final Asynccontext Asynccontext = Request.startasync ();  
          Sets the timeout period, and the program attempts to rerun the asynchronous task, which is our new thread, after the timeout.  
          Asynccontext.settimeout (10*1000l);  
             The new thread begins an asynchronous call, and the Start method is not blocking, it starts a new thread to start the Runnable interface, and then the main program continues execution Asynccontext.start (new Runnable () {  
                    public void Run () {try {thread.sleep (5*1000l); Out.println ("<p style= ' border:1px solid blue;") > Output after an asynchronous call。  
                    </p> ");  
                    Out.flush ();  
                    The asynchronous call completes, and if the complete () method is not invoked after the asynchronous call completes, the result of the asynchronous call needs to wait until the set timeout//time elapses before returning to the client.  
                Asynccontext.complete ();  
                catch (Exception e) {e.printstacktrace ();  
          }  
             }  

          }); Out.println ("<p style= ' border:1px solid red;") > May output before an asynchronous call, or after an asynchronous call, because the asynchronous call will start a new thread.  
          </p> ");  
    Out.flush (); }

}

Calling listeners asynchronously

   When we need to do a detailed listener for an asynchronous call, such as listening for a timeout, we can do this by setting the corresponding listener Asynclistener to the Asynccontext. Asynclistener is an interface that defines four methods, respectively, for the start, end, error, and timeout of an asynchronous call.
(3) File upload

Uploading files in Servlet3.0 becomes very simple. We simply obtain the part that corresponds to the uploaded corresponding file through the request's Getpart (String partname) or the GetParts () method to obtain the corresponding part for all uploaded files. Then we can write the corresponding file to disk through the part's write (String fileName) method. Or the part's getInputStream () method gets the input stream of the file and then operates on the input stream. To use the Getpart () or GetParts () method of the request to operate on the uploaded file, there are two places to note. First, the enctype of form forms for uploading files must be multipart/form-data, and secondly, for the servlet that uses the annotation declaration, we must use @multipartconfig to annotate the corresponding class. For the servlet configured in the Web.xml file, we also need to specify its multipart-config properties, such as:

XML code:

 <servlet> <servlet-name>xxx</servlet-name> <servlet-class>xxx.xxx</servlet-class > <multipart-config></multipart-config> </servlet> <servlet-mapping> <servlet- name>xxx</servlet-name> <url-pattern>/servlet/xxx</url-pattern> </servlet-mapping> fi Le-size-threshold: Numeric type that is written to the hard disk when the file size exceeds the specified size.

  The default is 0, which means that files of all sizes will be written to the hard disk as a temporary file after uploading. Location: Specifies the directory where the uploaded files are stored. When we specify the location, we can write the file to the hard disk by calling the part's write (String FileName) method, and the file name can be used without the path, but if FileName takes an absolute path,

  That will write the file to disk with the path of filename. Max-file-size: A numeric type that represents the maximum size of a single file. The default is-1, which means no limit.

  A IllegalStateException exception is thrown when a single file has a size that exceeds the value specified by Max-file-size. Max-request-size: A numeric type that represents the maximum size of an uploaded file at a time. The default is-1, which means no limit.



The illegalstateexception exception is thrown when all files are larger than max-request-size when uploaded. The above attributes are for configuring a servlet in Web.xml, where each of the attributes corresponds to a child element under the Multipart-config element. For a servlet based on the annotation configuration, the attributes of the @MultipartConfig are of type, we just need to remove the bar in the middle of the corresponding attribute, and then capitalize the corresponding letter, such as MaxFileSize. 
@WebServlet ("/servlet/upload") @MultipartConfig public class Fileuploadservlet extends HttpServlet {/** *  

   * Private static final long serialversionuid = 1L;  @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception,  
      IOException {req.setcharacterencoding ("UTF-8");  
      Part part = Req.getpart ("Upload"); Format such as: Form-data; Name= "Upload";  
      Filename= "YNote.exe" String disposition = Part.getheader ("content-disposition");  
      SYSTEM.OUT.PRINTLN (disposition);  
      String fileName = disposition.substring (disposition.lastindexof ("=") +2, Disposition.length ()-1);  
      String FileType = Part.getcontenttype ();  
      Long fileSize = Part.getsize ();  
      SYSTEM.OUT.PRINTLN ("FileName:" + filename);  
      System.out.println ("FileType:" + fileType);  
      System.out.println ("fileSize:" + fileSize); String Uploadpath = Req.getservletcontext (). Getrealpath ("/upload");  
      System.out.println ("Uploadpath" + Uploadpath);  
   Part.write (Uploadpath + file.separator +filename); For file uploads in Servlet3.0, there is also a need to note that when we write part to the hard disk, our original parts (that is, the previous temporary file) may have been deleted, and this time if we go back to the section, then it is empty, The system throws an exception saying that the corresponding file cannot be found.

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.