Analysis of features of Servlet2.5

Source: Internet
Author: User
Tags image filter

In this article, I mainly talk about the features in Servlet2.5. Describe each change, describe the background of the necessary changes, and demonstrate how to use these changes in Servlet-based projects. Introduce new features of Servlet to you. You can correctly determine which features and functions you can use, and which features and functions you should not use.

Note: When you want to practice the features and functions of these Servlets, you need to know that not all Servlet containers and Java enterprise-level application servers can immediately apply to the new Servlet APIs, apache Tomcat5.5 and Jboss 4.0 currently only support Servlet2.4.

Copyright Disclaimer: Any website authorized by Matrix must retain the following author information and links for reprinting.
Author: evenbetter
Original article:
Keyword: Servlet, 2.5

Introduction to some changes in Servlet2.5:

◆ Developed based on the latest J2SE 5.0.

◆ Annotations is supported.

◆ Configuration in web. xml is more convenient.

◆ Remove a few restrictions.

◆ Optimized some instances

J2SE 5.0 Product

From the very beginning, the Servlet 2.5 specification listed J2SE 5.0 (JDK 1.5) as its minimum platform requirement. It makes Servlet2.5 only applicable to platforms developed based on J2SE 5.0. This change means that all J2SE5.0 features can be useful to Servlet2.5 programmers.

Traditionally, Servlet and JEE versions have been developing in sync with JDK versions, but this time, Servlet versions have skipped version 1.4. The Expert Group believes that the accelerated growth of versions is justified because J2SE5.0 proposes a striking feature-Annotations that Servlet and JEE specifications must use.


Annotations is a new feature of Metadata proposed as part of jsr175. it facilitates Java language design. It is a decoration mechanism that uses Metadata for Java Encoding Structural classes, methods, domains, and so on. It cannot be executed like code, but can be used to mark code. This process is implemented by updating their event behavior based on the Code processor of Metadata information.

We can use different techniques to annotate classes and methods, such as marking interfaces consecutively or @ deprecated Javadoc comments. This new type of Metadata provides a standard mechanism to implement the annotation function, and creates your own annotation type variables through libraries.

The following is a simple Web service annotation example:

  1. import javax.jws.WebService;  
  3. import javax.jws.WebMethod;  
  5. @WebServicepublic class HelloWorldService {   
  7.  @WebMethod  public String helloWorld() {    
  9.   return "Hello World!";  }} 

The annotation types @ WebService and @ WebMethod are described in detail in the Web ServicesMetadata provided by JSR181 for the Java platform. They can be referenced like classes, mark this class as a Web service and mark its helloWorld) method as a Web service method. For them, the comment is only written there and does not have any function, as if to make a record on the job, but once a container loads this class and binary code those annotations, you can connect this class to the Web service.

Annotations can accept attributes/values. It stores parameter information and can be used to change the event behavior of the request. For example, the following more advanced annotation example:

  1. @WebService( name = "PingService",  targetNamespace=  
  3. @SOAPBinding(  style=SOAPBinding.Style.RPC,  use=SOAPBinding.Use.LITERAL)  
  5. public class Ping {  @WebMethod(operationName = "Foo")   
  7.  public void foo() { }} 

Once this class is loaded, a correctly configured container will recognize comments and their parameters, use this as a PingService to connect to a Foo operation by using the remote-procedure-call/literal encoding method. In fact, the annotation specifies the relationship between the class and the class container.

Java specification JSR175) has only a small number of annotation type variables. These interesting annotation type variables mainly come from other JSRs:

◆ JSR 250: public comments of the Java platform

◆ JSR 220: enterprise-level JavaBeans 3.0

◆ JSR 224: XML-based Java API Web Services (JAX-WS) 2.0

◆ JSR 181: Web Services Metadata of the Java platform

Notes in Servlet2.5:

Back to Servlet2.5, a new specification describes how several annotations work in the Servlet environment. Servlet containers with weak functions ignore these specifications, but servlets in the JEE container strictly abide by these specifications.

Some Annotations provide the selectivity for registering in XML. Otherwise, they must be registered in the configuration file web. xml. Some requests are used as containers to execute their tasks. Otherwise, the Servlet will execute the tasks in person. Other annotations are both available.

The exact annotation definition is not completely fixed because the Servlet itself does not define the annotation. It only explains how they affect the Servlet environment. The following is a brief overview of the annotations. You can see their usage in JEE5:

◆ @ Resource and @ Resources: @ Resource is located in the class or variable to "inject Resources" into the Servlet container ". When the container identifies this annotation, it will re-inject the annotated variable with appropriate values before obtaining the service status. By using this annotation, you do not need to use jndi to find commands and manually declare Resources in the configuration file web. xml. The server executes its tasks through Servlet self-adjustment. Variable names and types are automatically determined by the image mechanism, although you can use annotation parameters to go beyond this limit. An injected resource can be a data source, a Java information service target file, or a scalar set in the environment. The following is an example:

  1. @Resource javax.sql.DataSource catalog;  
  3. public getData() {  Connection con = catalog.getConnection();} 

Now, before the Servlet code becomes a service, the container locates the JNDI variable and manually allocates the directory variable.

For efficiency, only some classes support resource injection. These classes include: Servlets, Servlet filter, Servlet event listener, JSP tag operator, JSP library event listener, and JSF for processing beans, and some classes irrelevant to Serlvets.

◆ @ Resources annotation is similar to @ Resource, but it is used for a group of @ Resource annotations. They are all from JSR250, which is a public comment on the Java platform.

◆ @ PostConstruct and @ PreDestroy: A method with a life cycle can be used. @ PostConstruct method is used after resource injection initialization. @ PreDestroy: This method is used when the Servlet leaves the service and releases the injected resources. The reclaim method must be a fact method. The void is returned and no exception can be thrown. These annotations essentially make any method a sub-Method of init () and destroy (). These features also come from JSR250.

◆ @ EJB: similar to @ Resource, it is designed to inject enterprise-level JavaBeans. It is slightly different from @ Resource because @ EJB's parameter-specific design is used to locate EJB parameters. This comment comes from the EJB3.0 specification.

◆ @ WebServiceRef: similar to @ Resource and @ EJB, it is designed to inject Web service parameters. From JAX-WS2.0 specifications.

◆ @ PersistenceContext, @ PersistenceContexts, @ PersistenceUnit, and @ PersistenceUnits: These annotations come from EJB3.0 specifications to support Java object persistence.

◆ @ DeclareRoles: defines the use of security roles in applications. When defining a Servlet class, set it in the <security-role> label of the configuration file web. xml, from JSR250.

◆ @ RunAs: Declares which class should be executed. When defining a Servlet class, set it in the <run-as> label in the configuration file web. xml. From JSR250.

Annotation Efficiency

Whether you use annotations or not-especially when you are not in use-it is important to understand the execution of programs on the server. In order for the server to recognize comments in the class, it must load these classes, which means that the server must be started, the server looks for comments through all class files under the WEB-INF/classes directory and under the WEB-INF/lib directory. In each specification, the server does not need to find directories other than these two directories .) You can specify the attribute of <web-app> root through the following method without having to comment on it:

  1. ﹤web-app xmlns="" version="2.5" full="true"﹥  
  3. ﹤/web-app﹥ 

Convenience of web. xml

Servlet2.5 introduces several small changes to web. xml to make it more convenient.

Wildcard Servlet name
First, when you write <filter-mapping>, you can use the * number in the <Servlet-name> label to represent all Servlets. In the past, you had to bind a Servlet to a filter at a time, like this:

  1. ﹤filter-mapping﹥    
  2. ﹤filter-name﹥Image Filter﹤/filter-name﹥    
  3. ﹤Servlet-name﹥ImageServlet﹤/Servlet-name﹥  
  4. ﹤/filter-mapping﹥  

Now, you can bind all Servlets At A Time:

  1. <Filter-mapping>
  2. <Filter-name> Image Filter </filter-name>
  3. <Servlet-name> * </Servlet-name>
  4. <! -New Features -->
  5. </Filter-mapping>

This is useful, for example:

  1. ﹤filter-mapping﹥    
  2. ﹤filter-name﹥Dispatch Filter﹤/filter-name﹥   
  3.  ﹤Servlet-name﹥*﹤/Servlet-name﹥    
  4. ﹤dispatcher﹥FORWARD﹤/dispatcher﹥  
  5. ﹤/filter-mapping﹥ 

Ing compound mode

Secondly, when we write <Servlet-mapping> or <filter-mapping>, you can use the composite matching standard in the same tag. In the past, only one <Servlet-mapping> element <url-pattern> was supported. Currently, more than one element is supported, for example:

  1. ﹤Servlet-mapping﹥   
  2.  ﹤Servlet-name﹥color﹤/Servlet-name﹥    
  3. ﹤url-pattern﹥/color/*﹤/url-pattern﹥    
  4. ﹤url-pattern﹥/colour/*﹤/url-pattern﹥  
  5. ﹤/Servlet-mapping﹥ 

Similarly, in the past, <filter-mapping> only one <url-pattern> or one <Servlet-name> is supported. Now it supports any number of elements:

  1. ﹤filter-mapping﹥   
  2.  ﹤filter-name﹥Multipe Mappings Filter﹤/filter-name﹥    
  3. ﹤url-pattern﹥/foo/*﹤/url-pattern﹥   
  4.  ﹤Servlet-name﹥Servlet1﹤/Servlet-name﹥   
  5.  ﹤Servlet-name﹥Servlet2﹤/Servlet-name﹥    
  6. ﹤url-pattern﹥/bar/*﹤/url-pattern﹥  
  7. ﹤/filter-mapping﹥ 

HTTP Method Name

Recently, you can add valid HTTP/1.1 method names to the

If you write a WebDAV Servlet, you do not need to use the doLock () and doCopy () methods. You must write your own service () method and dispatch request. getMethod () method. Due to this change, you do not have to manage system security.

Remove restrictions

Servlet2.5 removes some restrictions on error handling and session tracking. For error handling, before Servlet2.5, the error handling page configured in <error-page> cannot be modified by calling the setStatus () method to trigger their error code, servlet2.5 weakens this specification. Such a rule is derived from the idea that the job of the error page is to point out every error rather than modify the error. However, in actual use, the error page is not only used to identify errors, but also to do more things. It may be used as an online help to help users solve problems. This specification will no longer limit the feedback information generated on the error page.

For session tracking, before Servlet2.5, the Servlet that calls RequestDispatcher. include () cannot set the response header, while Servlet2.5 weakens this specification. The purpose of the original specification is to restrict internal Servlets to its own page space and not affect external pages. Now this specification has been weakened, and the request. getSession () command can be used in the internal Servlet. This command can quietly create a session tracking cookie header. It is logically required to restrict internal resources, but it is also required that these restrictions should not cancel the function of starting the session. This change is especially important for the Portlet specifications. The function is: if the response is valid, the getSession () Command will throw an IllegalStateException (exception). This function is not available until now.


Recently, new specifications have explained some edge methods, making Servlets more convenient and better able to work as required.

Termination response

The first explanation is small and profound, but as an example of the specification, it is quite interesting. The Servlet2.4 specification specifies that the response should be valid in these situations, including: the content in the setContentLength method of the response has been explicitly stated, and the content has been written into the response. In this case, only your code like the following can redirect the response:

  1. response.setHeader("Host", "localhost");  
  3. response.setHeader("Pragma", "no-cache");  
  5. response.setHeader("Content-Length", "0");  
  7. response.setHeader("Location", ""); 

Servlet technology ignores the header of a specific region. Because the content must be 0 bytes long, the response takes effect immediately. Before it starts, the response becomes invalid!

Servlet containers usually refuse to perform this action, while Servlet2.5 adds the "length must be greater than 0" principle.

Instance code

The Servlet2.4 specification specifies that the request. setCharacterEncoding () method must be called before the request. getReader () method is called. However, if you ignore this principle and then call the request. setCharacterEncoding () method, what are the consequences? I didn't mention it in this question specification. To make it easy, eliminate this situation now!

Cross-context sessions (sessions between different context Directories)

Recently, the Cross-context session processing rules have been clearly stated. When Servlets assigns a request from one context to another, this rule takes effect-sessions included in the target call process. This version enables portlets on the home page of a context directory to work with portlets in other context directories through several internal commands. Servlet2.5 explicitly states that resources in a context directory can access sessions in other context directories without considering where the request starts. This means that portlets can run in its own scope out of the home page, and this specification will also be applied to incompatible Serlvet containers.


Because the Servlet2.5 version needs to maintain some old nature, several major concepts have to be postponed to the next stage. They include:

◆ New input/output (NIO) support: the NIO channel is more conducive to Servlets client communication.

◆ Filter wrap-under or wrap-over semantics: Sometimes the request is packaged with a filter, and/or the response object is used to modify the method behavior or enable a new method. How should I package this package together with the server's packaging of requests and responses?

◆ Welcome Servlets file: should the index serve as a welcome file? Before that, the answer is yes. However, the specification does not clearly describe how to use this function, especially when no index is available.

◆ Dispatch Rules for welcome documents: the details of how to dispatch welcome documents are not fully described, but some open gaps are left to address incompatibility issues.

◆ Select the default page after login: if the user accesses the Servlet login page through their bookmarks, where should the page be switched after successful login? This issue has not yet been clearly stated.

◆ User topic log: After the website is correctly registered, the Servlet cannot trust the user without the traditional login method.


If you leave comments aside to see the changes in Servlet2.5, it can be seen in the configuration file web. it is advantageous to remove some restrictions in xml, and optimizes the instance behavior so that it is more suitable for the development of Web Systems (Web pages ).

The comments in Servlet2.5 play a more dramatic role. Servlets itself cannot declare annotation-type variables, and even weak Servlet containers do not support annotation. However, Servlets writers in the JEE5 environment can see that the types of comments introduced through public comments and EJB3.0 and JAX-WS2.0 specifications will have a great change in the Code, this will also have a significant impact on how the Servlet manages external resources, Object persistence, and EJB composition.

  1. Get database connection in JSP
  2. Introduction to JSP Action
  3. When JSP is converted to Servlet
  4. Analysis of five common Servlet Methods
  5. Servlet/JSP Configuration

Related Article

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: 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.