Servlet 3.0 standard summary

Source: Internet
Author: User
Tags i18n

 

Directory

# Tomcat version

# Servlet

# ServletRequest

# Asynchronous Processing

# Servlet Context

# ServletResponse

# Filter

# Session

# Annotation

# Web fragment

# RequestDispatcher

# Web App

# Error handling

# Welcome Page

 

 

 

# Tomcat version

 

Tomcat 7.x: JDK 7/Servlet 3.0/JSP 2.2/EL 2.2

Tomcat 6.x: JDK 6/Servlet 2.5/JSP 2.1

 

 

# Servlet

 

Servlet interface: GenericServlet, HttpServlet

Generally, the container only creates one Servlet instance, and concurrent requests are processed by the same instance. Therefore, Servlet is NOT thread-safe.

If the Servlet implements SingleThreadModel, the container will create multiple instances to ensure that each instance runs only in one thread at the same time. However, SingleThreadModel is not recommended for specifications.

Two lifecycle callback Methods: init () and destroy ()

 

O path ing

 

Path format:

-If it starts with a slash (/) and ends with a slash (*), the longest match is used.

-The name starting with "*" must match with the extension.

-Null String (""), matching Context Path

-Only/character, matching the default Servlet

-All others must be matched strictly.

 

If multiple matches exist in a URL, the priority is:

-Strict matching

-Longest match

-Extension matching

 

 

# ServletRequest

 

Interface ServletRequest, HttpServletRequest

Class HttpServletRequestWrapper

 

O life cycle: after a request object expires, it may be reused after it is recycled by the container. Applications should not rely on request objects beyond the valid range.

 

O Request Parameters

The request parameters submitted by the client are read using the HttpServletRequest. getParameterXxx () method.

If the form data is submitted using the POST method, the encoding type must be application/x-www-form-urlencoded. The form data is used as the parameter. Otherwise, the form data is in the HTTP Request body, read Only through InputStream

File upload must use the multipart/form-data form Type and add the @ MultipartConfig flag to the Servlet.

Reading data uploaded to a file: getPart (), getParts ()

 

O attribute

Attribute is the container setting or application setting. The method is setAttribute (), getAttributeXxx ()

Attribute names starting with java, javax, and sun are retained

SSL-related attributes, which are provided by the container in the form of attributes

Determine whether SSL: isSecure ()

 

O HTTP header: getHeaderXxx (), getXxxHeader ()

 

O Request Path

The request path consists of three parts:

-Context Path: the root Path of the Web application. If the Web application is the default application, it is "", getContextPath ()

-Servlet Path: Servlet ing Path after Context Path

-Path Info: If the Servlet ing Path uses wildcards, the part after the Servlet Path is Path Info.

For example, if the host is www.the.com, the Web application is some. war, a Servlet ing path is/oneServlet/*, and the client requests http://www.the.com/some/oneservlet/any/file

-Context Path =/some

-Servlet Path =/oneServlet

-Path Info =/any/file

Ignore URL encoding. requestURI = contextPath + servletPath + pathInfo

 

O obtain the local path

You can convert the Request Path to the local file system path of the server.

-ServletContext. getRealPath (): converts the Path of the Context Path to a local physical Path.

-HttpServletRequest. getPathTranslated (): converts the Path Info of the request to a local physical Path.

 

O getCookies () get cookies

 

O I18N

The Accept-Language header in the HTTP request, which can be read using the following methods: getLocale (), getLocales ()

 

O Request character encoding

GetCharacterEncoding (), returns null if the client is not specified (Content-Type header), the container uses ISO-8859-1 by default

SetCharacterEncoding () overwrites the character encoding submitted by the client

 

 

# Asynchronous Processing

 

If the Servlet. service () method needs to wait for another resource to be available, such as database connection, it will lead to thread waiting, reducing the thread utilization of the container.

The basic idea of asynchronous processing is that the application starts a sub-thread and executes the work that causes the thread to wait in the sub-thread so that the service () can return the result as soon as possible.

ServletRequest. startAsync () enables the request to enter asynchronous mode. In asynchronous mode, exiting service () does not submit Response to the client, but waits

-Asynchronous processing is completed. By calling AsyncContext. complete () to notify the container, AsyncContext is returned by startAsync ()

-Asynchronous processing timeout

(Personal retention of application threads in Web containers)

 

# Servlet Context

 

ServletContext is the Web app access interface

The path of the Web app on the server is http: // host: port/contentRoot.

Each Web app has only one ServletContext instance.

 

O initialization parameters

Settings: Use web. xml

Read: getInitParameterXxx ()

 

O added Servlet, Filter, and Listener for programming.

ServletContext provides a method to create and configure Servlet, Filter, and Listener during Web app initialization, as declared in web. xml

-AddServlet/Filter/Listener ()

-CreateServlet/Filter/Listener ()

-GetServlet/Filter/ListenerRegistration ()

-GetServlet/Filter/ListenerRegistrations ()

 

O attribute

The attribute object of ServletContext can be accessed by any component in the Web app.

-SetAttribute ()

-GetAttribute ()

-GetAttributeNames ()

-RemoveAttribute ()

 

O read Resources

Attackers can read static resource files in Web apps, such as HTML.

-GetResource ()

-GetResourceAsStream ()

 

O Temporary Folder

The container must provide a temporary folder for each Webapp.

File dir = (File) servletContext. getAttribute ("javax. servlet. context. tempdir ");

 

 

# ServletResponse

 

HTTP response returned by HttpServletResponse to the client

The ServletResponse object should be in its valid range only

 

O Buffer

The data returned from the client can be written through OutputStream or PrintWriter, or the buffer can be written before being submitted to the client.

ServletResponse provides the following methods:

-GetBufferSize ()

-SetBufferSize ()

-Reset ()

-ResetBuffer ()

-FlushBuffer ()

-IsCommitted ()

 

O HTTP Header

SetHeader ()

AddHeader ()

SetXxxHeader ()

AddXxxHeader ()

 

O Convenient Method

-SendRedirect () redirection

-SendError (): return the HTTP Error Page

 

O I18N

-SetLocale ()

-SetContentType ()

-SetCharacterEncoding ()

 

# Filter

 

Interface Filter

The filter can modify the Request and Response objects before the Request arrives at the Servlet.

You can also modify the Response after Servlet processing and before sending it to the client.

The filter can modify the Request or Response header by wrapping (Wrap ).

Lifecycle: init (), doFilter (), destroy ()

During init (), the Container provides the FilterConfig parameter.

-Get the initialization parameter: getInitParameterXxx ()

-Retrieve ServletContext: getServletContext ()

DoFilter () receives the FilterChain parameter and must explicitly call its doFilter () method to call the next filter.

After the next Filter. doFilter () is executed, you can modify the Response object.

The Filter. doFilter () in FilterChain forms a function call stack. Therefore, the program flow is a reciprocating process along the FilterChain. It first passes through each Filter from the beginning to the end, and then returns to the first Filter in reverse order.

 

O Filter configuration

First, configure Filter in web. xml.

......... 

Set Filter ing in two ways:

............

Under <filter-mapping>, <servlet-name> and <url-pattern> can appear multiple times, and both of them can appear, for example:

...............

The order of the FilterChain associated with a Servlet or other Web resources (such as JSP and HTML) is

-The first step is to use the Filter mapped by <url-pattern>. If there are multiple filters, follow the ing Declaration

-Then, use the <servlet-name> ing Filter. If there are multiple filters, follow the ing Declaration

<Filter-mapping> can contain <dispatcher> sub-elements, as shown in figure

REQUESTINCLUDE

<Dispatcher> values:

-REQUEST: When this Filter is applied to requests from the client

-FORWARD: this Filter is applied to ForwardDispatcher. forward ()

-INCLUDE: this Filter is applied to ForwardDispatcher. include ()

-ERROR: this Filter is applied to the ERROR page.

-ASYNC: this Filter is applied to Async context dispatch)

If no <dispatcher> is specified, a REQUEST is generated.

 

# Session

 

Web containers automatically maintain sessions using the following methods:

-Cookie: the Cookie name is JSESSIONID.

-SSL Session: SSL already has a Session.

-URL rewriting: append the URL; jsessionid = xxx

If the browser disables cookies, the container considers each request as a new Session.

Session. isNew ()

Applications can store custom objects in the Session with attributes: setAttribute (), getAttribute ()

You can use HttpSessionBindingListener to listen for changes to property objects.

Session Timeout: setMaxInactiveInterval (), getMaxInactiveInterval (),-1 indicates never timeout

GetLastAccessedTime () gets the last accessed time

 

O URL rewriting

When URL rewriting technology is used, the service provided by the container is to extract the Session ID from the request URL, which does not need to be processed by the application. However, the application needs to dynamically append all URLs to all pages; jsessionid = xxx

URL rewriting can be used in GET and POST methods.

 

# Annotation

 

Web. xml description file root element <web-app> metadata-complete attribute specifies whether only web. xml is used

If metadata-complete = "false", the container searches for Annotation.

 

-@ WebServlet: Servlet

-@ WebFilter: used for Filter

-@ WebInitParam is used for Servlet and Filter

-@ WebListrener: used for various listeners

-@ MultipartConfig: This Annotation is required for servlets that support form file upload.

 

 

# Web fragment

 

Package WebApp components (classes) into different jar packages, and declare and configure the components in the package in the jar package/META-INF/web-fragment.xml, similar to web. xml

Such a jar package is called Web fragment.

The web-fragment.xml root element is <web-fragment>

The web-fragment.xml is invalid (same as Annotation) When <web-app metadata-complete = "true"> in web. xml)

The name (such as <servlet-name>) must be unique in web. xml and all Web fragment. Different Web fragment and web. xml cannot have the same name.

 

# RequestDispatcher

 

Obtain RequestDispatcher

-ServletContext. getRequestDispatcher ()

-ServletContext. getNamedReuquestDispatcher ()

-HttpServletRequest. getRequestDispatcher ()

Append a Query string to the parameter URL)

 

Include ()

Forward ()

-The contained Servlet cannot modify the HTTP header of the Response object.

-Before forward (), the Container clears the Response content. After forward (), the container sends the Response content to the client and closes

 

# Web App

 

O directory structure

The Virtual Path after the Context path in the client request URL)

The virtual path can be relative:

-Web app (*. war) Root, recorded/

-/WEB-INF/lib/Under the jar package/META-INF/resources/

Former priority

/All resources under the WEB-INF cannot be publicly accessed by the client, but can be read by the Servlet, or accessed through RequestDispatcher

Exception: resources under the jar package/WEB-INF/resources/Under the/META-INF/lib can be publicly accessed by the client

 

# Error handling

 

When an exception thrown by HttpServletResponse. sendError () or a Servlet/Filter is caught by the container, different error pages can be returned to the client based on the HTTP status code or exception type.

The ing between HTTP status code and exception types and error pages is configured in web. xml.

        /some/page.jsp      404      java.io.IOException  

 

# Welcome Page

 

When the requested URL of the client specifies that the resource does not exist, add a welcome page after the URL in turn. If a welcome page exists, return it to the client.

    index.html    index.htm    index.jsp    default.html    default.htm    default.jsp  

The welcome page can contain subdirectories, but it cannot start or end /.

When the container matches the welcome page, it first matches static resources and then Servlet Path ing.

 

 

 

 

 

 

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.