Share new features about Servlet2.5

Source: Internet
Author: User
Tags error code error handling event listener execution header connect new features variables
Servlet

September 26, 2005, a new version of the Servlet API is released by the Group of experts from Sun and JSR154. In general, a new version of a JSR consists only of removing updates to a few previously nominal specifications. But this time, the new version adds new features and changes that have a significant impact on the Servlets, making the servlet version rise to 2.5.

In this article, I mainly talk about the new features in the Servlet2.5 version. Describe each change, explain the background of the necessary changes, and show how to take advantage of these changes in a servlet based project.

In fact, this is the sixth article I've provided for Javaworld about the servlet API update. This article is intended for two purposes: to introduce you to the new features of the servlet from the immediate perspective. In the long run, it's a historical summary of the changes in the servlet, so that when you encode based on the old Servlet API version, you can correctly determine which features and features you can use, and which features and features you shouldn't use. You can refer to my previous article on the servlet.

Note: When you want to practice the new features and features of these servlet, you need to know that not all servlet containers and Java Enterprise Application servers can immediately apply to the latest version of the servlet API, when writing this article (January 2, 2006), Jetty 6 Server and Sun's GlassFish server are recognized as the best support for Servlet2.5 containers, while Apache Tomcat5.5 and JBoss 4.0 currently support only Servlet2.4.
Servlet2.5 Introduction to some changes:

1) based on the latest J2SE 5.0 development.
2) Support comments.
3) Several configurations in the Web.xml are more convenient.
4) to go except for a few restrictions.
5) Some examples are optimized

Product of J2SE 5.0:
From the outset, the Servlet 2.5 specification lists J2SE 5.0 (JDK 1.5) as its minimal platform requirements. It makes Servlet2.5 only suitable for platforms based on J2SE 5.0 development, which means that the new features of all j2se5.0 are guaranteed to be useful to Servlet2.5 programmers.
Traditionally, the servlet and JEE versions have been synchronized with the JDK version, but this time, the servlet version skipped version 1.4. The group believes that the accelerated growth of the version is justified because j2se5.0 presents a compelling feature that the servlet and JEE specifications are to exploit?? Comments.

Note:
Annotations are a new language feature presented as part of the JSR175 (a metadata that facilitates the design of the Java language). It is a mechanism for using metadata to decorate Java coded structures (classes, methods, domains, etc.). It can't be executed like code, but it can be used to tag code, a process based on metadata information that is implemented by updating their event behavior.

We can annotate classes and methods with different techniques, such as continuously labeling interfaces or @deprecated Javadoc reviews. This new metadata is a convenient way to provide a standard mechanism to implement annotation functions and to create variables for users ' own annotation types through libraries.

Here is a simple example of a Web service annotation:
Import Javax.jws.WebService;
Import Javax.jws.WebMethod;
@WebService
public class HelloWorldService {
@WebMethod
Public String HelloWorld () {
Return "Hello world!";
}
}
The two annotation types, @WebService and @webmethod, are described in detail in JSR181 (Web Servicesmetadata provided for the Java platform) and can be referenced as a class, marking this class as a web Service and marks its HelloWorld () method as a Web service method. For themselves, annotations are only written there and have little effect, as if they were recorded on the job, but once a container loads the class and binaries the annotations, it can connect the class to the Web service.
Note You can accept properties/values for these parameters. It holds information about the parameters and can take advantage of these parameters to change the requested event behavior. For example, the following more advanced annotation examples:
@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 properly configured container will recognize the annotation and its arguments, and make this a pingservice by using remote-procedure-call/literal encoding to connect to an Foo operation. In fact, the annotation indicates the relationship between the class and the container of the class.

The specification for Java itself (JSR175) has only a small number of annotation type variables. And these interesting annotation type variables are mainly from other JSRs:
Public annotations for the JSR 250:java platform
JSR 220: Enterprise Class JavaBeans 3.0
JSR 224: xml-based java API Web Services (JAX-WS) 2.0
Web Services Metadata for JSR 181:java Platform
Comments in Servlet2.5:
Back to Servlet2.5, a new specification describes how several annotations work in a servlet environment. The weak servlet container ignores these specifications, whereas the servlet in the Jee container strictly adheres to these specifications.

Some annotations provide selectivity in XML registrations, otherwise they are registered in the configuration file Web.xml. There are requests to perform their tasks as containers, or the servlet will execute them in person. There are also notes that are both available.

The exact definition of the annotation is not completely fixed, because the servlet itself does not define the annotation. It only explains how they affect the servlet environment, and here is a brief overview of the annotations, and you can see what they are used for in JEE5:

• @Resource and @Resources: "Resource injection" of the servlet container @Resource in a class or variable. When the container recognizes this annotation, it implements the re-injection of the annotated variable with the appropriate value before obtaining the service status. By using this annotation, you do not have to use Jndi to find commands and manually declare resources in the configuration file Web.xml. The server performs its tasks through a servlet's self-regulation. The name and type of the variable are automatically determined by the imaging mechanism, although you can use the parameters of the annotation to override this limitation. An injected resource can be a data source, a Java Information service destination file, or a scalar that is set by the environment. Here is an example:
@Resource Javax.sql.DataSource Catalog;
Public GetData () {
Connection con = catalog.getconnection ();
}
Now, before this servlet code becomes a service, the container locates the Jndi variables and assigns them manually to the directory variables.
For efficiency, only certain classes support resource injection, these classes are: Servlets,servlet filter, servlet event Listener, JSP tag operator, JSP library event listener, for handling beans JSF, and some serlvets-independent classes.
• @Resources annotation is similar to @resource, but it is used for a set of @resource annotations. They are all from JSR250 and are public annotations of the Java platform.
• @PostConstruct and @PreDestroy: You can make a method a method with a lifecycle. @PostConstruct method is used after resource injection initialization. @PreDestroy method is used when the servlet is detached from the service and frees injected resources. The reclaimed method must be a method of fact, return void and no exception can be thrown. These annotations essentially make any method a child of Init () and Destroy (), which are also derived from the JSR250.
• @EJB: Similar to @resource, designed to inject enterprise-class JavaBeans. It is slightly different than @resource, where the parameters of the @ejb are specifically designed to locate the EJB's parameters. This annotation is from the EJB3.0 specification.
• @WebServiceRef: Similar to @resource and @EJB, designed to inject Web service parameters. From the jax-ws2.0 specification.
• @PersistenceContext, @PersistenceContexts, @PersistenceUnit, and @PersistenceUnits: These comments come from the EJB3.0 specification to support the persistence of Java objects.
• @DeclareRoles: Define the use of security roles in your application. When a servlet class is defined, it is set in the <security-role> tab of the configuration file Web.xml from JSR250.
• @RunAs: Used to declare which class should be executed. When you define a servlet class, set it in the <run-as> tab of the configuration file Web.xml. From the JSR250.

The execution of the note:
Whether you use annotations or not?? Especially when you're not using it? It is important for understanding the execution of programs on the server. In order for the server to identify annotations in the class, it must load these classes, which means that the server must be started, and the server looks for annotations through all the class files in the Web-inf/classes directory and the Web-inf/lib directory. (under each specification, the server does not have to look for directories outside these two directories.) You can use the following method to indicate the properties of the <web-app> root without using how to comment:
<web-app xmlns= "Http://java.sun.com/xml/ns/javaee"
version= "2.5" full= "true" >
</web-app>
The convenience of Web.xml:
SERVLET2.5 introduces several small changes to web.xml, making it more convenient.
Wildcard Fu Hua for servlet names:
First, when you write <filter-mapping&gt, you can now use the * number in the <Servlet-name> tag to represent all servlets. In the past, you had to bind a servlet to a filter one 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 the servlets at once:

<filter-mapping>
<filter-name>image filter</filter-name>
<Servlet-name>*</Servlet-name> <!? New Feature-->
</filter-mapping>

This has a lot of uses, such as:

<filter-mapping>
<filter-name>dispatch filter</filter-name>
<Servlet-name>*</Servlet-name>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>

Composite mode of mapping:
Second, when we write <Servlet-mapping> or <filter-mapping>, you can now use composite matching criteria in the same label. A previous <Servlet-mapping> supported only one <url-pattern> element, and now it supports not only one, for example:
<Servlet-mapping>
<Servlet-name>color</Servlet-name>
<url-pattern>/color/*</url-pattern>
<url-pattern>/colour/*</url-pattern>
</Servlet-mapping>

In the same way, previously <filter-mapping> only supported one <url-pattern> or one <Servlet-name>. Now it can support any number of elements for each element:

<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 put the legal http/1.1 method name into the If you write a WebDAV servlet, you do not have to use the Dolock () and Docopy () methods. You must write your own service () method and assign the Request.getmethod () method. Because of this change, you don't have to manage the security of your system.
Removal Restrictions:

Servlet2.5 removes some of the restrictions on error handling and reply tracking. For error handling, the error-handling page configured in <error-page> cannot modify the error code that triggers them by calling the SetStatus () method, and Servlet2.5 weakens the specification before Servlet2.5. Such a specification arises from the view that the job of the error page is to point to each error instead of modifying it. However, in practice, the error page is not just for pointing out errors, but it can do more things, perhaps instead of online help to help users solve problems. This specification will no longer limit the feedback generated by the error page.

For session tracking, the servlet calling Requestdispatcher.include () cannot set the header of the response before Servlet2.5, and Servlet2.5 weakens the specification. The purpose of the original specification is to limit the internal servlets to its own page space and not to affect the external pages. This specification is now weakened, allowing the request.getsession () command to be used in the internal servlet, which silently creates a session-tracking cookie header. It is logically required to limit internal resources, but it is also logically required that these restrictions should not cancel the ability to start the session. This change is particularly important for portlet specifications. The effect is: if the response is already valid, the getsession () command throws a IllegalStateException (exception), which is not available until then.

Optimization:
Recently, the new specification optimizes some examples to make servlets more convenient and ensures better job requirements.

To terminate a response:
The first optimization is small and esoteric, but as an example of the specification, it's quite interesting. The Servlet2.4 specification stipulates that the response should be valid in these situations, including: the content is clearly stated in the response's Setcontentlength method, and the content is already written in the response. In this case, only your code can redirect the response as follows:

Response.setheader ("Host", "localhost");
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Content-length", "0");
Response.setheader ("Location", "http://www.apache.org");

The servlet technology ignores the header headers for a particular area because the content is 0 bytes long and the response takes effect immediately. And before it starts, the response is invalidated! servlet containers generally refuse to perform this behavior, whereas the Servlet2.5 version adds the principle of "length must be greater than 0".
Instance encoding:

The Servlet2.4 specification requires that the Request.setcharacterencoding () method be called before the Request.getreader () method is invoked. However, if you ignore this principle and then invoke the Request.setcharacterencoding () method after it, then what will happen, the problem is not stated in the specification. For simplicity, now eliminate this situation!
Cross-context sessions (sessions between different context directories):
Recently, the rules for Cross-context session processing have been clearly stated. This rule works when Servlets assigns a request from one context to another context.? Which sessions are included in the target invocation process. The advent of this version allows portlets in a context directory's home page to work on portlets in other context directories through several internal commands. Servlet2.5 explicitly indicates that a resource in a context directory can access the session of the other context directory, regardless of where the request started. This means that portlets can run in its own range from the scope of the home page, and this specification will also be applied to incompatible serlvet containers.
Expect:

With the Servlet2.5 version to maintain some of the old nature, several large concepts have to be postponed to the next stage. They include:
• New input/output (NIO) Support: It is possible to make the NIO channel more conducive to servlets client communication.
• Filter Wrap-under or wrap-over semantics: Sometimes the filter wraps the request, and/or the response object modifies the method behavior or enables the new method. How should this packaging be packaged together with the server's packaging of requests and responses?
• Servlets files for welcome: Do you want to be a welcome file for indexing? Before that, the answer was yes. However, the specification does not specify how to use this feature, especially in the absence of an index.
• Allocation rules for welcome files: How to assign a welcome file, this detail is not fully explained, but it left some open gaps to deal with incompatibility issues.
• Select the default page after login: If the user accesses the Servlet landing page through their bookmarks, where should the page turn after the successful landing? This question has not yet been clearly stated.
• User's subject log: After registering correctly through the website, there is no way to make the servlet trust the user without the traditional way of landing.
Conclusion:
If you leave out the comment to see Servlet2.5 changes, it is obvious that in the configuration file Web.xml in addition to some restrictions, is advantageous, but also optimizes the instance behavior makes it more suitable for the development web System (webpage).
Annotations in Servlet2.5 are more dramatic. Servlets itself cannot declare a variable of annotation type, even a weak servlet container does not support annotations. However, the Servlets writers in the JEE5 environment can see that annotation types introduced through public annotations and EJB3.0 and jax-ws2.0 specifications can make a big difference to code, and this will have a significant impact on how the servlet manages external resources, the persistence of objects, and the composition of EJBS.



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.