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:

Remote Port: 3303 Local Name: localhost Local Addr: 127.0.0.1 Local Port: 8080
New features 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 properties that will be added to a Request object 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 values of these properties are null. On the other hand, these attributes will have non-null values in the resources passed to the object. These property values are useful when a resource must only be called from another resource and not directly.

For example, in a Context called myApp there is a servlet named ModernServlet and ModernServlet is passed to TargetServlet. In TargetServlet, the code in Listing 2 is displayed.

The deployment descriptor of myApp 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 displayed by the console when calling ModernServlet:

javax.servlet.forward.request_uri: /myApp/Modernjavax.servlet.forward.context_path: /myAppjavax.servlet.forward.servlet_path: /Modernjavax.servlet.forward.path_info: null javax.servlet.forward.query_string: null
Use filters for request schedulers. Servlet 2.4 added a new element to the deployment descriptor to allow servlet programmers to decide whether to apply filters to the request dispatcher. Element values can be REQUEST (default), FORWARD, INCLUDE, and ERROR:

REQUEST. Use a filter if the request comes directly from the client.
FORWARD. If the request is being processed by the request dispatcher, indicating that a matching or matching web component uses a pass-through call, a filter is used.
INCLUDE. Filters are only used when a request is being processed by the request dispatcher, indicating that a matching or matching web component uses an include call.
ERROR. Filters are only used when the request is being processed by the error page mechanism as an error resource that matches the element.
Servlet 2.4 only supports HTTP 1.1 clients. Servlet 2.3 supports both HTTP 1.0 and HTTP 1.1. Unlike Servlet 2.3, Servlet 2.4 only supports HTTP 1.1 clients. As a transition, the HTTP / 1.0 status code 302 (temporary recommendation) still exists and is still represented by SC_MOVED_TEMPORARILY in the javax.servlet.http.HttpServletResponse interface. HTTP 1.1 has a Found status code of 302, which is represented by the static SC_FOUND in the HttpServletResponse interface.

Servlet is used as welcome page. In Servlet 2.3, you can use the element in the deployment descriptor to list the welcome files--the 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 elements. 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, if the user types a URL such as http: // domain / context / (without a resource file), ModernServlet is called.

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 shown below:

response.setLocale (locale);
This means you must first create a Locale object.

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

setContentType ('text / html; charset = UTF-8');
In Servlet 2.4, there are two new methods in the javax.servlet.ServletResponse interface that support internationalization. The first method is setCharacterEncoding, which is used as follows:

public voidsetCharacterEncoding (String charset)
With setCharacterEncoding, you can specify only the character encoding as a string without having to first create a Locale object. Note, however, that for this method to work, it must be called before the getWriter method is called and before the response is submitted.

The second new method is getContextType, which is the result of calling the setContentType, setLocale, or setCharacterEncoding method in the ServletResponse object, which returns the content type used in the ServletResponse object.

In addition to these two methods in javax.servlet.ServletResponse, you can also use Servlet 2.4 to define a new element in the deployment descriptor: it saves the servlet programmer from having to specify a locale-to-charset in his / her servlet Mapping. An example of how to use this new element is as follows:

<locale-encoding-mapping-list> <locale-encoding-mapping> <locale> ja </ locale> <encoding> ISO-2022-JP </ encoding> </ locale-encoding-mapping> </ locale-encoding- mapping-list>
Extensibility of deployment descriptors. In a Servlet 2.3 application, the deployment descriptor is validated against a DTD file. Servlet 2.4 now supports validation of deployment descriptors against patterns. The use mode has the following advantages over using the DTD:

A pattern can inherit the syntax of another pattern (extensible).
Mode is more accurate than DTD.
The pattern lets you specify the actual data type of the content of each element.
Patterns can be used in multiple namespaces.
The pattern allows you to specify the maximum and minimum number of times an element appears.
However, for backward compatibility, the Servlet 2.4 container is required to support Servlet 2.3 and Servlet 2.2 DTDs.

The javax.servlet.SingleThreadModel interface is not supported. The SingleThreadModel interface has no methods. It is used to indicate to the servlet container that it must guarantee that no two threads will simultaneously execute the service method of the servlet implementing the interface. From the beginning of servlet technology to the present, people have generally misunderstood this interface. Everyone is against using it now because it causes confusion and gives the servlet programmer an illusion of security when considering thread safety. This interface should never be used again in any new development work.

New features in JSP 2.0

JSP 2.0 (originally called JSP 1.3) is a significant improvement over JSP 1.2. Of course, the most important addition is the support for the Expression Language (EL) in the JSP 2.0 container.

EL was originally defined by the JSP Standard Tag Library (JSTL) 1.0 specification, which assists in removing Java code from JSP pages. The API described in the javax.servlet.jsp.el package reveals the semantics of EL. The semantics of EL expressions are similar to those of Java expressions; the value of the expression is calculated and inserted into the current output. ELs can be used in standard or custom operation attribute values as well as in template text. The following is the structure of an EL expression (where expr is an expression):

$ {expr}
For literal values containing the character sequence "$ {", JSP 2.0 provides a way to escape by using the sequence "$ {'$ {'". For example, the following character sequence is converted to the literal value $ {expr}:

$ {'$ {'} expr}
In addition, since EL versions prior to JSP 2.0 do not support EL, JSP applications will ignore EL in any web applications whose web.xml is validated against Servlet 2.2 or Servlet 2.3 DTD. In order to test the expression in the JSP page described here, you just need to delete the web.xml file from your application.

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

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

pageContext. PageContext object
pageScope. Map page-wide attribute names to their values
requestScope. Map request-scoped attribute names to their values
sessionScope. Maps session-wide attribute names to their values
applicationScope. Map application-wide property names to their values
param. Maps a parameter name to a single string parameter value
paramValues. A string array that maps the parameter names to all the values of the parameter
header. Maps the header name to a single string header value
headerValues. Maps the header name to the header 

A string array of all the values in the header
cookie. Mapping cookie names to a single cookie object
initParam. Maps the 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, which is an easier way to write a 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 tag processors implementing the Tag interface, the most basic case is that the JSP container calls the doStartTag and doEndTag methods each time it encounters a tag in a JSP page. With JSP 2.0, JSP programmers can choose a tag handler with a simpler implementation process by implementing the new SimpleTag interface. The JSP container does not call the two methods of the tag handler implementing the Tag interface, but only needs to call one method in the SimpleTag interface: doTag. All tagging logic, iterative operations, and subject evaluation are performed in this way. Therefore, SimpleTag is as powerful as javax.servlet.jsp.tagext.BodyTag, but the operation process is simpler.

To support the writing of tag processors that need to implement the SimpleTag interface, the javax.servlet.jsp.tagext package provides a support class named SimpleTagSupport. If you want to extend this class, you only need to provide a method to execute: doTag.

Listing 3 shows an example of a tag handler that extends SimpleTagSupport.

Use tag files to develop tag libraries more easily. As we all know, custom tag libraries in JSP 1.2 take a lot of time to develop. Development work involves the development of tag processors and tag library descriptor (TLD) files, and registration of tag libraries in the web.xml file. JSP 2.0 solves this problem by providing a new way to write custom tag libraries. Using tag files, tag extensions can be similar to JSP files. No compilation, no editing of web.xml files, and no TLDs required. All you have to do is copy the tag files into the WEB-INF / tags directory, and this is easy to do. The rest is left to the JSP container, which will convert each tag file found in the WEB-INF / tags directory into a tag handler. The programmer completely gets rid of the complicated work of building a tag processor.

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

<% — Example1.tag file, must reside in WEB-INF / tags —%> <% out.println ("Hello from tag file.");%>
Using tag libraries in JSP pages couldn't be easier. As usual, you only need the taglib directive to identify the tag library throughout the page via the prefix attribute. Now you have a tagdir attribute, not a uri attribute. The tagdir attribute references the WEB-INF / tags directory or any subdirectory under WEB-INF / tags.

The following is an example of a JSP page using the example1.tag file.

<% @ taglib prefix = "easyTag" tagdir = "/ WEB-INF / tags"%> <easyTag: example1> </ easyTag: example1>
Calling this JSP page browser will display the following string:

Hello from tag file.
Combined with the expression language mentioned above, you can really quickly build scriptless JSP pages. As another example, the following tag file (called example2.tag) receives a property by calling a JSP page and converts it to uppercase letters.

<% — Example2.tag file, must reside in WEB-INF / tags —%> <% @ attribute name = "x"%> <% x = x.toUpperCase (); out.println (x);%>
Here is the JSP page that uses the tag file:

<% @ taglib prefix = "easyTag" tagdir = "/ WEB-INF / tags"%> <easyTag: example2 x = "hello"> </ easyTag: example2>
Here is another example without 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 />
This tag file is used for the following JSP pages:

<% @ 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 />
Please note that to run this example, you need the JSTL library in the WEB-INF / lib directory.
The last markup file example also shows that page creators unfamiliar with the Java programming language can still take advantage of the power of markup extensions. Even Java programmers can use tag files more easily than writing Java classes that implement an interface in the javax.servlet.jsp.tagext package.

  in conclusion

This article briefly describes the new features in the Servlet 2.4 and JSP 2.0 specifications, which will be included in the forthcoming J2EE 1.4. Servlet 2.4 and JSP 2.0 will undoubtedly accelerate the development of Web applications.

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