Servlet and JSP on a new level

Source: Internet
Author: User
Tags filter array expression header new features string version java web
Js|servlet

The upcoming Java EE 1.4 provides a new servlet 2.4 and JavaServer Pages (JSP) 2.0 technology for developing Web applications in the JavaScript. This article shows the new features of both technologies and provides sample code for each feature where appropriate. This article assumes that the reader is familiar with the previous Servlet 2.3 and JSP 1.2 versions. The examples given are tested with Tomcat 5 (included in Java Web Services Developer Pack 1.2).

The servlet and JSP are undoubtedly two of the most widely used Java EE technologies. Servlet technology is the foundation of Web application Programming in Java, and also the basis of JSP. However, servlet programming can be very cumbersome. This is especially true when you have to send a long HTML page with little code. Each HTML tag must be embedded in a string and sent with the display of the PrintWriter object. It's a tedious and boring job. Another disadvantage of using the servlet is that every change requires a servlet programmer to intervene.

When Sun learned about the problem, it developed a JSP as a solution. In JSP, the division between the programmer and the page designer becomes much easier and compiles automatically when the JSP page changes. Note, however, that JSP is an extension of the servlet technology rather than an obsolete servlet. In practical applications, the servlet and JSP pages work together.

New features of Servlet 2.4

Servlet 2.4 provides several new classes and does not support the Javax.servlet.SingleThreadModel interface. This version only supports HTTP 1.1, so the servlet 2.4 application does not apply to HTTP 1.0 clients. Version 2.4 Adds a request listener and request property listener, and can use the servlet as a welcome page in one application. In addition, the Servlet 2.4 provides better servletrequest and RequestDispatcher objects, and better supports internationalization. In addition, it is now time to verify that the deployment descriptor is valid based on the schema rather than the document type definition (document-type definition,dtd) file. This means that the extensibility of the deployment descriptor is supported.

The new features of servlet 2.4 are described below. Request listener and Request property listener. Servlet 2.3 Adds servlet context-related listeners and session-related listeners. Servlet 2.4 Adds new Javax.servlet.ServletRequestListener and Javax.servlet.ServletRequestAttributeListener two interfaces that will notify you of events related to the Request object. If you are interested in initializing and undoing each request object, you can implement the Servletrequestlistener interface. This interface has two methods: Requestinitialized () and requestdestroyed (). When a request object is required, the servlet container invokes the Requestinitialized method. When the request object is no longer needed, the servlet container invokes the Requestdestroyed method.

Both methods receive a Javax.servlet.ServletRequestEvent object from the servlet container. The servlet context and servlet requests can be obtained from the Servletrequestevent instance.

The second listener Interface Servletrequestattributelistener processing the Add, change, and delete properties of the request object. The interface has the following methods:

    • Attributeadded. Called by the servlet container when new attributes are added to the Request object.

    • Attributeremoved. Called by the servlet container when a property is removed from the request object.

    • attributereplaced. Called by the servlet container when existing property values in the Request object are replaced.

These three methods obtain an instance of the Javax.servlet.ServletRequestAttributeEvent class from the servlet container. The Servletrequestattributeevent class extends the Servletrequestevent class and adds two new methods: GetName and GetValue. The GetName method returns the name of the property that triggered the event, GetValue returns the value of the property.

Listing 1 shows a sample class of these two new listeners. Both display the method name when the Servlet container invokes the method. After the listeners have been compiled, their class files must be deployed to the Web-inf/classes directory. The new method in ServletRequest. In Servlet 2.4, the Javax.servlet.ServletRequest interface adds 4 new methods:

    • Getremoteport. Returns the Internet Protocol (IP) source port of the client that sent the request or the last proxy server.

    • Getlocalname. Returns the hostname of the IP interface from which the request was received.

    • Getlocaladdr. Returns the IP address of the interface from which the request was received.

    • Getlocalport. Returns the IP port number from the interface from which the request was received.

Note that in Servlet 2.3, the values returned by the getServerName and Getserverport methods are the values returned by now Getlocalname and Getlocalport. In version 2.4, getServerName and Getserverport have been redefined. For more information, check out the API documentation.

The code in a JSP page is shown below--

Out.println ("<br>remote Port:" +   Request.getremoteport ()); Out.println ("<br>local Name:" +   Request.getlocalname ()); Out.println ("<br>local Addr:" +   request.getlocaladdr ()); Out.println ("<br >local Port: "+  Request.getlocalport ());

--The code generates something like this:

The new attribute of the request scheduler. Use the request scheduler to pass the current request to a new resource, or to introduce another resource from the current page. Servlet 2.4 Adds some properties that will be added to a request object that is passed to another resource:

Javax.servlet.forward.request_urijavax.servlet.forward.context_pathjavax.servlet.forward.servlet_ Pathjavax.servlet.forward.path_infojavax.servlet.forward.query_string

If a request object is not passed, the value of these properties is null. On the other hand, these properties will have a Non-null value in the resource being passed to the object. These property values are useful when a resource must be invoked only through another resource and cannot be called directly.

For example, in a context called MyApp, there is a servlet named Modernservlet, Modernservlet is passed to Targetservlet. In Targetservlet, the code in Listing 2 is displayed.

The MyApp deployment descriptor contains the following and elements:

<servlet>   <servlet-name>Modern</servlet-name>   <servlet-class>modernservlet   </servlet-class></servlet><servlet-mapping>   <servlet-name>modern</ servlet-name>   <url-pattern>/Modern</url-pattern> </servlet-mapping><servlet>   <servlet-name>Target</servlet-name>   <servlet-class>targetservlet   </ Servlet-class></servlet><servlet-mapping>   <servlet-name>Target</servlet-name>    <url-pattern>/Target</url-pattern></servlet-mapping>

The following is the result of the console display when calling Modernservlet:

Javax.servlet.forward.request_uri:/myapp/modernjavax.servlet.forward.context_path:/ MyAppjavax.servlet.forward.servlet_path:/modernjavax.servlet.forward.path_info:nulljavax.servlet.forward.query _string:null

Use the filter for the request scheduler. Servlet 2.4 Adds a new element to the deployment descriptor so that the servlet programmer decides whether to apply the filter (filters) to the request scheduler. The value of the element can be request (default), FORWARD, include, and error:

    • REQUEST. If the request comes directly from the client, the filter is used.

    • FORWARD. If the request is being processed by the request dispatcher, the filter is used to indicate that the Web component that matches or is using a pass-through call.

    • INCLUDE. A filter is used only if the request is being processed by the request dispatcher, and the Web component that matches it is used with the include (include) call.

    • ERROR. Use a filter only if the request is being processed by the error page mechanism as an error resource that matches the element.

Servlet 2.4 supports only HTTP 1.1 clients. Servlet 2.3 supports both HTTP 1.0 and HTTP 1.1, and servlet 2.4 is different from servlet 2.3, and it only supports HTTP 1.1 clients. As a transition, the http/1.0 status Code 302 (tentatively recommended) still exists and is still represented by the sc_moved_temporarily in the Javax.servlet.http.HttpServletResponse interface. HTTP 1.1 has the found status code 302, which is represented by the static sc_found in the HttpServletResponse interface.

The servlet is used as a welcome page. In Servlet 2.3, you can use elements in the deployment descriptor to list welcome files-Files that will be displayed when an incomplete URL is received. However, in Servlet 2.3, only HTML files or JSP files can be used in the element. In Servlet 2.4, a servlet can now be used as a welcome page. The following example is a servlet called modern, whose class is Modernservlet.class and has been mapped to Path/modern.

<servlet>  <servlet-name>Modern</servlet-name>  <servlet-class>modernservlet  </servlet-class></servlet><servlet-mapping>  <servlet-name>modern</ Servlet-name>  <url-pattern>/Modern</url-pattern></servlet-mapping>< Welcome-file-list>  <welcome-file>Modern</welcome-file></welcome-file-list>

At this point, Modernservlet is invoked when the user types a URL such as http://domain/context/(without a resource file).

New support for internationalization. In Servlet 2.3, there is no way to directly tell the client what character encoding the browser should use. To achieve this, you must pass a Java.util.Locale object to the SetLocale method of the Javax.servlet.ServletResponse interface, as follows:

Response.setlocale (locale);

This means that you must first create a locale object.

Alternatively, in Servlet 2.3, you can use the setContentType method to pass content types and character sets, such as:

setContentType (' text/html;               Charset=utf-8 ');

In Servlet 2.4, there are two new ways to support internationalization in the Javax.servlet.ServletResponse interface. The first method is setcharacterencoding, and its usage is as follows:

Public voidsetcharacterencoding (String CharSet)

With setcharacterencoding, you can specify only the character encoding as a string without having to create the locale object first. Note, however, that to make this method work, it must be called before the Getwriter method is invoked and before the response is committed.

The second new method is Getcontexttype, as a result of invoking the setContentType, setlocale, or Setcharacterencoding method in the Servletresponse object, It returns the type of content used in the Servletresponse object.

In addition to the two methods in Javax.servlet.ServletResponse, you can also use servlet 2.4 to define a new element in the deployment descriptor: It allows the servlet programmer to not have to Specifies the locale-to-charset mapping in her servlet. Examples of how to use this new element are as follows:

<locale-encoding-mapping-list>  <locale-encoding-mapping>    <locale>ja</locale>    <encoding>ISO-2022-JP</encoding>  </locale-encoding-mapping></ Locale-encoding-mapping-list>

Scalability of the deployment descriptor. In the servlet 2.3 application, the deployment descriptor is validated against the DTD file. The servlet 2.4 now supports validation of the deployment descriptor based on the schema. Using schemas has the following advantages over using DTDs:

    • A pattern can inherit the syntax of another schema (extensible).

    • Schemas are more accurate than DTDs.

    • You can specify the actual data type of the content of each element through a pattern.

    • Patterns can be used with multiple namespaces.

    • You can specify the maximum and minimum number of occurrences of an element through a pattern.

However, for backward compatibility, the Servlet 2.4 container is required to support the servlet 2.3 and servlet 2.2 DTDs.

The Javax.servlet.SingleThreadModel interface is not supported. The Singlethreadmodel interface has no method, which is used to indicate to the servlet container that it must ensure that no two threads execute the service method of the servlet that implements the interface at the same time. This interface has been widely misunderstood since the servlet technology began to appear. Now everyone is against it because it creates confusion and gives the servlet programmer an illusion of security when considering thread safety. This interface should never be used in any new development effort.

New features in JSP 2.0

JSP 2.0 (originally called JSP 1.3) has an important improvement over JSP 1.2. Of course, the most important additions are the inclusion of support for expression language (EL) in the JSP 2.0 container.

El was originally defined by the JSP standard Tag Library (JSTL) 1.0 specification to assist in removing Java code from JSP pages. The APIs described in the Javax.servlet.jsp.el package reveal the semantics of El. The semantics of an El expression are similar to that of a Java expression, and the value of an expression is computed and inserted into the current output. El can be used in property values for standard or custom operations, as well as in template text. The following is the structure of the El expression (where expr is an expression):

${EXPR}

For literal values that contain the character sequence "${", JSP 2.0 provides a way to change the code by using the sequence "${' ${'". For example, the following sequence of characters is converted to literal value ${expr}:

${' ${'}expr}

In addition, because the previous version of JSP 2.0 does not support El, the JSP application ignores El in any Web application, and the web.xml of those applications are validated against the servlet 2.2 or servlet 2.3 dtd. To test the expression in the JSP page described here, you only need to remove the Web.xml file from the application.

In fact, El is a simple language that helps page creators access JSP hidden objects, perform repetitive operations and conditional operations that do not contain Java code--which is not possible in JSP 1.2.

To access suppressed objects, the JSP container supports the following name-object mappings:

    • PageContext. PageContext objects

    • Pagescope. Mapping page-wide property names to their values

    • Requestscope. Map the request-scoped property names to their values

    • Sessionscope. Map the session-scoped property names to their values

    • Applicationscope. Mapping application-scoped property names to their values

    • Param Mapping parameter names to a single string parameter value

    • Paramvalues. A string array that maps parameter names to all values of the parameter

    • Header Map header names to a single string header value

    • Headervalues. A string array that maps header names to all values of the header

    • Cookie To map a cookie name to a single Cookie object

    • Initparam. Maps a context initialization parameter name to its string parameter value

For example, the following expression represents the value of the parameter username:

${param.username}

The following expression returns the value of the ProductID property of the Session object:

${sessionscope.productid}

Simpler Simpletag interface operation process. JSP 2.0 provides a new interface Javax.servlet.jsp.tagext.SimpleTag, a simpler way to write a tag processor (tag handler). In JSP 1.2, the tag processor must directly or indirectly implement one of the following interfaces in the Avax.servlet.jsp.tagext package: Tag, Iterationtag, or Bodytag. For a tag processor that implements the tag interface, the most basic scenario is that the JSP container calls the doStartTag and Doendtag two methods each time it encounters a tag in the JSP page. Using JSP 2.0,jsp programmers can choose a more simple tag processor by implementing a new Simpletag interface. The JSP container does not invoke two methods of the tag processor that implements the tag interface, but only one method in the Simpletag interface is called: Dotag. All tag logic, repetitive operations, and body evaluations are performed using this method. So, Simpletag is as powerful as the JAVAX.SERVLET.JSP.TAGEXT.BODYTAG function, but the process is simpler.

To support the authoring of tag processors that require the implementation of the Simpletag interface, the Javax.servlet.jsp.tagext package provides a support class called Simpletagsupport. If you want to extend this class, you only need to provide an execution method: Dotag.

Code Listing 3 shows an example of an extended Simpletagsupport tag processor.

Using tag files makes it easier to develop tag libraries. As we all know, the custom tag library in JSP 1.2 takes a lot of time to develop. Development work involves the development of tag processor and tag Library descriptor (TLD) files, and the registration of tag libraries in web.xml files. JSP 2.0 solves this problem by providing a new way to write a custom tag library. With tag files, markup extensions can resemble JSP files. No compilation, no editing of web.xml files, and no need for TLD. The thing to do is that you have to copy the tag file into the Web-inf/tags directory, which is easy to do. The rest is given to the JSP container, which converts each tag file found in the Web-inf/tags directory to a tag processor. Programmers are completely out of the complex work of building tag processors.

Here's an example. This is the simplest form of a tag library, where a tag file simply writes a string to an implied object.

<%-example1.tag file, must reside in       web-inf/tags-%><%  out.println ("Hello from tag file."); %>

It's easy to use a tag library in a JSP page. As usual, you only need to taglib instructions to identify the tag library throughout the page with the prefix attribute. Now you have a Tagdir attribute, not a URI attribute. The Tagdir property refers to any subdirectories under the Web-inf/tags directory or web-inf/tags.

The following is an example of a JSP page that uses the Example1.tag file.

<%@ taglib prefix= "Easytag"           tagdir= "/web-inf/tags"%><easytag:example1></easytag:example1>

Calling the JSP page browser displays the following string:

Hello from tag file.

With the expression language mentioned above, you can really quickly build a script-free JSP page. To take another example, the following tag file (called Example2.tag) receives a property by invoking the JSP page and converts it to uppercase.

<%-example2.tag file, must reside in     web-inf/tags-%><%@ attribute name= "x"%><%  x = X.touppercas E ();  OUT.PRINTLN (x);%>

The following is a JSP page that uses the tag file:

<%@ taglib prefix= "Easytag" tagdir= "/web-inf/tags"%><easytag:example2 x= "           Hello" ></easytag: Example2>

Here is another example, where there is no Java code:

<%-example3.tag file, must     reside in web-inf/tags-%><%@ variable name-given= "x"            scope= "At_begin"% ><%@ taglib prefix= "C"                      uri= "Http://java.sun.com/jsp/jstl/core"%><c:set var= "x" value= "3"/>after : ${x}<jsp:dobody/>

The tag file is used for the following JSP page:

<%@ taglib prefix= "C"          uri= "Http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix= "Easytag"          Tagdir = "/web-inf/tags"%><c:set var= "x" value= "1"/>before: ${x}<br><easytag:example3/>
Note that to run this example, there will be a jstl library under the Web-inf/lib directory.

The last tag file example also shows that page creators who are unfamiliar with the Java programming language can still take advantage of the powerful capabilities of markup extensions. Even for Java programmers, it is easier to use tag files than to write Java classes that implement an interface in the Javax.servlet.jsp.tagext package.

Conclusions

This article briefly describes the new features in the servlet 2.4 and JSP 2.0 specifications, which will be included in the upcoming Java EE 1.4. Servlet 2.4 and JSP 2.0 will undoubtedly speed up the development of Web applications.



Related Article

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.