- 浏览: 1397222 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (328)
- JSF (27)
- 生活 (12)
- Ajax (26)
- Maven (6)
- CSS (1)
- Shale (3)
- SiteMesh (1)
- Ext (15)
- JMX (2)
- Windows技巧 (7)
- 工作感悟 (18)
- SVN (2)
- SVG (0)
- GoogleGear (0)
- RAP (2)
- SOA与WebService (3)
- 笔记本技术研究 (1)
- Microsoft (2)
- 英语学习 (3)
- PHP (7)
- web 2.0 (6)
- 语义Web (1)
- IT史话 (3)
- iText (3)
- JVM (1)
- PropertiesEditor (1)
- J2SE (33)
- Spring (2)
- Java Batch (1)
- log (2)
- Struts2 (2)
- DWR (0)
- JAAS (3)
- EJB3 (4)
- Flex (8)
- JFreeChart (1)
- WAS (0)
- 数据库 (2)
- 摄影 (0)
- SQL (1)
- Google App Engine (1)
- linux (5)
- Eclipse plugin (10)
- Testing (0)
- Portal (0)
- 移动互联网 (0)
- SWTBot (1)
最新评论
-
江奇缘:
不错!!!!!!
web.xml里<filter-mapping>中的<dispatcher>作用 -
yy8093:
commonj 第三步,那个调用的方法要在哪里调?servle ...
JAVA中多种计时器的比较与分析 -
di1984HIT:
学习了,不错~
web.xml里<filter-mapping>中的<dispatcher>作用 -
penkee:
com.lowagie.text.DocumentExcept ...
iText中输出 中文 -
氵壞男亼乀:
我想请问下 你哪个html里面引入的几个js文件没看懂!你 ...
DWR入门教程之HelloWorld
New features added to Servlet 2.5
Please remember: When experimenting with these new features and capabilities, not all servlet containers or Java Enterprise Edition (JEE) application servers jump immediately to the latest Servlet API release. At the time of this writing, the Jetty 6 server and Sun's GlassFish server are the two best-known servlet containers that include 2.5 support. Apache Tomcat 5.5 and JBoss 4.0 still support Servlet 2.4.
Among the changes introduced in Servlet 2.5:
- A new dependency on J2SE 5.0
- Support for annotations
- Several web.xml conveniences
- A handful of removed restrictions
- Some edge case clarifications
Dependency on J2SE 5.0
To begin with, the Servlet 2.5 specification now lists J2SE 5.0 (JDK 1.5) as its minimum platform requirement. While this limits Servlet 2.5 to those platforms with J2SE 5.0 implementations, this change means that all the new language features from J2SE 5.0 (generics, autoboxing, an improved for loop, a new enum type, static importing, varargs, and metadata annotations) are guaranteed available to Servlet 2.5 programmers.
Traditionally, servlet and JEE releases have moved forward at the measured pace of one JDK level at a time, but this time, the servlet release skipped version 1.4. The expert groups considered the double jump to be justified because J2SE 5.0 offered one compelling feature that the servlet and JEE specifications wanted to use themselves: annotations.
Annotations
Annotations are a new language feature provided as part of JSR 175 (A Metadata Facility for the Java Programming Language). Annotations provide a mechanism for decorating Java code constructs (classes, methods, fields, etc.) with metadata information. Annotations aren't executed like code, but, rather, mark code in such a way that code processors may alter their behavior based on the metadata information.
When you think about it, we've been annotating classes and methods all along with different tricks like the Serializable marker interface (to alter serialization) or the @deprecated Javadoc comment (to alter compilation). The new metadata facility simply provides a standard mechanism for doing annotations and a vehicle for libraries to create custom annotation types.
Here's a simple Web service annotation example:
import javax.jws.WebService; import javax.jws.WebMethod; @WebService public class HelloWorldService { @WebMethod public String helloWorld() { return "Hello World!"; } }
The @WebService and @WebMethod annotation types, specified in JSR 181 (Web Services Metadata for the Java Platform) and imported just like classes, mark this class as a Web service and mark its helloWorld() method as a Web service method. By themselves, the annotations don't do anything but sit there, kind of like Post-It notes; however, a container, upon loading this class and seeing those annotations in the bytecode, can wire up the class for Web services.
Annotations may accept name/value parameters. The parameter information is kept with the annotation and can be used to alter the behavior requested by the annotation. For example, here's a 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() { } }
Upon loading this class, a proper container will respect the annotations and their parameters, and wire up the class as a PingService with a Foo operation using the remote-procedure-call/literal encoding style. In a sense, annotations define the contract a class wishes to have with its container.
The Java language itself (through JSR 175) specifies only a tiny number of annotation types. The interesting annotation types come from other JSRs:
- JSR 250: Common Annotations for the Java Platform
- JSR 220: Enterprise JavaBeans 3.0
- JSR 224: Java API for XML-Based Web Services (JAX-WS) 2.0
- JSR 181: Web Services Metadata for the Java Platform
See Resources for more details on metadata and annotations.
Annotations in Servlet 2.5
Coming back to Servlet 2.5, the new specification describes how several annotations work in a servlet environment. Simple servlet containers can ignore these rules, while servlets in a JEE container must abide by them.
Some annotations provide an alternative to XML entries that would otherwise go in the web.xml deployment descriptor. Other annotations act as requests for the container to perform tasks that otherwise the servlet would have to perform itself. Some annotations do both.
The exact list of annotations isn't completely finalized, because the Servlet specification itself doesn't define the annotations; it only helps interpret how they affect a servlet environment. Here's a short summary of the annotations you can expect in JEE 5 along with their intended use:
- @Resource and @Resources: @Resource is placed on a class or variable to request a "resource injection" by the servlet container. When the container sees this annotation, it will prepopulate the annotated variable with an appropriate value before the servlet gets placed into service. By using this annotation, you avoid the need to make a JNDI (Java Naming and Directory Interface) lookup call and declare the resource manually in the web.xml deployment descriptor file. The server takes care of both tasks through introspecting the servlet. The name and type of the variable are determined automatically by reflection, although you can override that with annotation parameters. An injected resource may be a datasource, Java Message Service destination, or environment entry variable. Here's a basic example:
@Resource javax.sql.DataSource catalog; public getData() { Connection con = catalog.getConnection(); }
Now, before putting a servlet with this code into service, the container will locate the JNDI variable named catalog of type DataSource and manually assign that reference to the catalog variable.
For efficiency, only certain classes support resource injection: servlets, servlet filters, servlet event listeners, JavaServer Pages tag handlers and JSP library event listeners, JavaServer Faces scoped managed beans, and a few other class types unrelated to servlets.
The @Resources annotation is similar to @Resource, but used to hold an array of @Resource annotations. Both annotations are from JSR 250, the Common Annotations for the Java Platform.
Annotation performance
Whether or not you use annotations—and especially if you don't—it's important to understand the performance impact they can have on a server at startup. In order for the server to discover annotations on classes, it must load the classes, which means that at startup, a server will look through all the classes in WEB-INF/classes and WEB-INF/lib, looking for annotations. (Per the specification, servers don't have to look outside these two places.) You can avoid this search when you know you don't have any annotations by specifying a metadata-complete attribute on the <web-app> root like this:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5" metadata-complete="true"> </web-app>
web.xml conveniences
Servlet 2.5 introduces several small changes to the web.xml deployment descriptor file format to make its use more convenient.
Servlet name wildcarding
First, when writing a <filter-mapping>, you can now use an asterisk in a <servlet-name> entry to represent all servlets (and thus all JSP pages as well). Previously, you could only bind one servlet at a time to a filter, like this:
<filter-mapping> <filter-name>Image Filter</filter-name> <servlet-name>ImageServlet</servlet-name> </filter-mapping>
Now you can bind all servlets at once:
<filter-mapping> <filter-name>Image Filter</filter-name> <servlet-name>*</servlet-name> <!-- New --> </filter-mapping>
This proves most useful when creating general rules like, "Execute a filter on all forwards to a servlet," which is written like this:
<filter-mapping> <filter-name>Dispatch Filter</filter-name> <servlet-name>*</servlet-name> <dispatcher>FORWARD</dispatcher> </filter-mapping>
Multiple patterns in mappings
Second, when writing a <servlet-mapping> or <filter-mapping>, you can now provide multiple match criteria in the same entry. A <servlet-mapping> previously supported just one <url-pattern> element. Now it supports more than one. For example:
<servlet-mapping> <servlet-name>color</servlet-name> <url-pattern>/color/*</url-pattern> <url-pattern>/colour/*</url-pattern> </servlet-mapping>
Likewise, a <filter-mapping> previously allowed just one <url-pattern> or one <servlet-name>. Now it supports any number of each:
<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>
Both these changes are syntactic sugar, but so be it. There's no reason we should program low carb.
HTTP method names
Lastly, you can now place any legal HTTP/1.1 method name into an <http-method> element. As you may recall, the <http-method> element specifies the methods on which a <security-constraint> entry should apply. It's historically been limited to the seven standard HTTP/1.1 methods: GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE. However, HTTP/1.1 allows for extension methods, and WebDAV is a popular technology using extensions. With Servlet 2.5, you can now apply security constraints on any conceivable HTTP method name, standard or extension, including WebDAV methods like LOCK, UNLOCK, COPY, and MOVE.
Just don't look for doLock() or doCopy() methods if you're writing a WebDAV servlet. You'll have to write your own service() method and peek at the request.getMethod() for dispatching. You just won't have to manage your own security, thanks to this change.
Restriction removal
Servlet 2.5 eased a few restrictions around error handling and session tracking. With error handling, Servlet 2.5 removed a rule dictating that error-handling pages configured with <error-page> could not call setStatus() to alter the error code that triggered them. The rule followed the argument that the job of an error page is to report each error but not alter it. However, practical use has made clear that sometimes an error-handling page may be able to do something more graceful than show an error, perhaps choosing instead to show an online help chat window to help the user resolve the problem. The specification no longer prevents an error-page handler from producing a nonerror response.
Regarding session tracking, Servlet 2.5 eased a rule dictating that a servlet called by RequestDispatcher include() couldn't set response headers. This rule's purpose was to keep included servlets constrained within their own space on the page, unable to affect the page outside that area. The rule has eased now to allow request.getSession() calls within the included servlet, which might implicitly create a session-tracking cookie header. Logic dictates an included resource should be constrained, but logic also dictates those constraints shouldn't eliminate the ability to initiate a session. This change proves especially important for the Portlet Specification. Note that if the response was already committed, the getSession() call will throw an IllegalStateException. Previously, it would have been a no-op.
Clarifications
Lastly, the new specification clarifies several edge cases to make servlets more portable and guaranteed to work as desired.
Response closure
The first clarification is trivial and esoteric, but interesting as an example of the unintended side effects you sometimes see in a specification. The Servlet 2.4 specification dictates that the response should be committed (that is, have the response started with the status code and headers sent to the client) in several situations including when "The amount of content specified in the setContentLength method of the response and has been written to the response." This appears all well and good until you write code like this to do a redirect:
response.setHeader("Host", "localhost"); response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Length", "0"); response.setHeader("Location", "http://www.apache.org");
The servlet technically must ignore the Location header because the response must be committed immediately as the zero byte content length is satisfied. The response is over before it began! Servlet containers often refuse to implement this behavior, and the Servlet 2.5 release adds "has been greater than zero" to the rule.
Encoding edge cases
The Servlet 2.4 specification says you must call request.setCharacterEncoding() before calling request.getReader(). However, it does not say what happens if you ignore this advice and make the setter call after the retrieval. For portability, it's now clarified to be a no-op.
Cross-context sessions
Lastly, the rules around cross-context session management have been clarified. This comes into play when servlets dispatch requests from one context to another. Within the target call, what session should be in scope, if any? The issue came up most prominently with portlets, where a main page in one context may do several include calls to portlets in another context. Servlet 2.5 now specifies that resources within a context see the session for that context, regardless of where the request may have started. This means the portlets can track their own state separate from the main page state, and this rule will apply across servlet containers.
Still on the wish list
Because of the maintenance review nature of the Servlet 2.5 release, several larger ideas had to be postponed until the next review phase. Among the ideas postponed:
- New Input/Output (NIO) support: It's possible NIO Channels would be a more efficient way for servlets to communicate with clients.
- Filter wrap-under or wrap-over semantics: People sometimes use filters to wrap the request and/or response objects to alter method behavior or expose new methods. When this wrapping is combined with a server's need to wrap the request and response as part of a request dispatch, how do the wraps fit together?
- Servlets as welcome files: Should an index.do be able to act as a welcome file? Historically, the answer has been yes. But the specification doesn't clarify how to allow that functionality, especially if no index.do is on the filesystem, but a *.do mapping is, which would always exist virtually and shadow other welcome files.
- Welcome file dispatch rules: The details on how to dispatch to welcome files have not been exhaustively specified and leave open cracks for incompatibility.
- Selecting a default page after login: If users visit a servlet's form-based login page from their bookmarks, where should they be sent after a successful login? It's unspecified today.
- Programmatically log in a user: Right after a user registers with a site, there's no way to inform the servlet environment about the user's credentials without the user performing a traditional login.
Update: March 6, 2006
After this article was first published, Sun issued a Servlets 2.5 MR2 (second manufacturing release) that includes a few changes from the first manufacturing release:
- The attribute full on the <web-app> root was renamed to the more descriptive metadata-complete. This change has been incorporated into the above text.
- A new method getContextPath() was added to ServletContext. Formerly context path information was only available in the request object, following the logic that the same context object might be bound to multiple paths so you'd only know the path at request time. However, no known servers have utilized the multiple path binding option, and a context being able to report its path is often convenient, so the method got the green light. Should it ever happen that a context be bound to multiple paths, it will return its "preferred" path.
Conclusion
If you look at the Servlet 2.5 changes apart from annotations, the new release does a nice job of giving web.xml a little syntactic sugar, of removing a few restrictions that were getting in the way, and of clarifying edge case behavior to enable more powerful and portable component-based Webpages.
The effect of annotations in Servlet 2.5 looks more dramatic. It's important to remember that servlets themselves don't define any new annotation types, and simple servlet containers don't even have to support annotations. Yet servlets authored for a JEE 5 environment will see their code change a lot from the annotation types introduced by common annotations and the EJB 3.0 and JAX-WS 2.0 specifications, and these will have a big impact on how servlets manage external resources, object persistence, and EJB components.
Author Bio
Jason Hunter is author of the book Java Servlet Programming, 2nd Edition (O'Reilly, 2001; ISBN: 0596000405) and coauthor of Java Enterprise Best Practices (O'Reilly, 2002; ISBN: 0596003846). He's an Apache Member and, as Apache's representative to the Java Community Process Executive Committee, he established a landmark agreement for open source Java. He's publisher of Servlets.com, an original contributor to Apache Tomcat, and cocreated the open source JDOM library to enable optimized Java and XML integration. He also designed and developed CountryHawk, a product that quickly determines a user's country based on their IP address.
相关推荐
To help you sort out which features were added in which release, we provide two tables. Features Added to JDK 1.1 and Enhanced in JDK 1.2. summarizes the features added to JDK 1.1, with notes about ...
You may consider this whitepaper a companion document to these walkthroughs, complementing them with a focus on the overall language features and how they work, as opposed to the specifics of the ...
Enhance your development skills with Java's state-of-the-art features and projects to make your applications leaner and faster Key Features Overcome the challenges involved in migrating to new ...
Oracle Database 12c Release 2 New Features 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 查看此书详细信息请在美国亚马逊官网搜索此书
This course is designed to introduce you to the new features of Oracle Database 10g that are applicable to the work usually performed by database administrators and related personnel. The course does ...
Version 2.5 Attention : This version is not compatible with releases before FCKeditor 2.5.1. <br>New Features and Improvements: <br>[#1548] Compatible with Safari 3.0+ and Opera 9.50+....
Brian Taylor, Naresh Adurty, Steve Bradley, and Carrie King Taylor with Mark A. Shelton and Jagan Reddy Wordware Publishing,
practical techniques that you can immediately implement in your PHP projectGrow your PHP skillset with the newest language features and modern best practicesGet up to speed on new language features ...
Implement the new features central to Swift Testing and understand the new debug features Create server-side applications using Swift 3 Table of Contents Chapter 1: What Were They Thinking? Chapter 2:...
easily configured for high-power, high-gain applications with super power-added efficiency while operating over the 2.4~2.5GHz frequency band. The YP242034 is assembled in a 16-pin, 4×4mm2, QFN ...
good_features_to_track.pdf ,一个支持NCC匹配的算法,挺好的
With announcement of Odoo 10, there are many new features added to Odoo and the face of business applications developed with Odoo has changed. This book will not only teach you how to build and ...
This revision of SysML relies on several new features incorporated into UML 2.5. Any use of the term “UML 2” or “UML” in this specification, unless otherwise noted, will refer to UML 2.5 in ...
Microsoft SQL Server 2005新特性。
一本书 Addison.Wesley.Microsoft.SQL Server 2000-A Guide to Enhancements and New Features
Invocation Options ?Environment variables ?Lexical entities : keywords,...Features added in 2.5 since 2.4 Features added in 2.4 since 2.3 Originally based on: ?Python Bestiary, author: Ken Manheimer
Swift 3 New Features 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
Swift 3 New Features 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除