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: http://www.javaworld.com/javaworld/jw-01-2006/jw-0102-servlet.html
Http://www.matrix.org.cn/resource/article/44/44208_Servlet+2.5.html.
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
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:
- import javax.jws.WebService;
-
- import javax.jws.WebMethod;
-
- @WebServicepublic class HelloWorldService {
-
- @WebMethod public String helloWorld() {
-
- 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:
- @WebService( name = "PingService", targetNamespace=http://acme.com/ping)
-
- @SOAPBinding( style=SOAPBinding.Style.RPC, use=SOAPBinding.Use.LITERAL)
-
- public class Ping { @WebMethod(operationName = "Foo")
-
- 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:
- @Resource javax.sql.DataSource catalog;
-
- 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:
- ﹤web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5" full="true"﹥
-
- ﹤/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:
- ﹤filter-mapping﹥
- ﹤filter-name﹥Image Filter﹤/filter-name﹥
- ﹤Servlet-name﹥ImageServlet﹤/Servlet-name﹥
- ﹤/filter-mapping﹥
Now, you can bind all Servlets At A Time:
- <Filter-mapping>
- <Filter-name> Image Filter </filter-name>
- <Servlet-name> * </Servlet-name>
- <! -New Features -->
- </Filter-mapping>
This is useful, for example:
- ﹤filter-mapping﹥
- ﹤filter-name﹥Dispatch Filter﹤/filter-name﹥
- ﹤Servlet-name﹥*﹤/Servlet-name﹥
- ﹤dispatcher﹥FORWARD﹤/dispatcher﹥
- ﹤/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:
- ﹤Servlet-mapping﹥
- ﹤Servlet-name﹥color﹤/Servlet-name﹥
- ﹤url-pattern﹥/color/*﹤/url-pattern﹥
- ﹤url-pattern﹥/colour/*﹤/url-pattern﹥
- ﹤/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:
- ﹤filter-mapping﹥
- ﹤filter-name﹥Multipe Mappings Filter﹤/filter-name﹥
- ﹤url-pattern﹥/foo/*﹤/url-pattern﹥
- ﹤Servlet-name﹥Servlet1﹤/Servlet-name﹥
- ﹤Servlet-name﹥Servlet2﹤/Servlet-name﹥
- ﹤url-pattern﹥/bar/*﹤/url-pattern﹥
- ﹤/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.
Clarifications
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:
- response.setHeader("Host", "localhost");
-
- response.setHeader("Pragma", "no-cache");
-
- response.setHeader("Content-Length", "0");
-
- response.setHeader("Location", "http://www.apache.org");
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.
Expectation
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.
Conclusion
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.
- Get database connection in JSP
- Introduction to JSP Action
- When JSP is converted to Servlet
- Analysis of five common Servlet Methods
- Servlet/JSP Configuration