Servlet and JSP have taken a new step

Source: Internet
Author: User
Tags cookie names tld
Developers JSP

Servlet and JSP have taken a new step

Author: Budi kurniawan

The new servlet 2.4 and assumerver pages 2.0 technologies will better serve us.

The upcoming J2EE 1.4 provides Java-based Web Application DevelopmentProgramThe new servlet 2.4 and JavaServer Pages (JSP) 2.0 technologies. This article demonstrates the new features of these two technologies and provides examples of each feature in an appropriate placeCode. This document assumes that you are familiar with the previous servlet 2.3 and JSP 1.2 versions. The example has been tested using Tomcat 5 (included in Java Web Services developer pack 1.2.

Servlet and JSP are undoubtedly the two most widely used J2EE technologies. Servlet technology is the basis for Web application programming using Java and also the basis of JSP. However, Servlet programming may be very troublesome. 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 as a printwriter object. It is a tedious and annoying job. Another disadvantage of using Servlet is that each change requires the involvement of servlet programmers.

Sun developed JSP as a solution after learning about this problem. In JSP, the division of labor between programmers and page designers is much easier, and the JSP page is automatically compiled when it is changed. However, note that JSP is an extension of Servlet technology, rather than discarding servlet. In practical applications, Servlet and JSP pages are used 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 servlet 2.4 applications are not applicable to HTTP 1.0 client programs. Version 2.4 adds request listeners and request property listeners, and can use servlets as welcome pages in an application. In addition, Servlet 2.4 provides better servletrequest and requestdispatcher objects, and better supports internationalization. In addition, the deployment descriptor is verified based on the document-type definition, DTD, instead of the document type definition file. This means that deployment descriptor scalability is supported.

The following describes the new features of servlet 2.4. Request listener and request property listener. Added servlet context-related listeners and session-related listeners in servlet 2.3. Servlet 2.4 adds the new javax. servlet. servletrequestlistener and javax. servlet. servletrequestattributelistener interfaces, which will notify you of the events related to the request object. If you are interested in the initialization and revocation of 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 calls the requestinitialized method. When the request object is no longer needed, the servlet container calls the requestdestroyed method.

Both methods receive a javax. servlet. servletrequestevent object from the servlet container. You can obtain servlet context and Servlet requests from the servletrequestevent instance.

The second listener interface servletrequestattributelistener processes the addition, modification, and deletion of request object attributes. This interface has the following methods:

    • Attributeadded. The servlet container calls the request object to add a new property.

    • Attributeremoved. The servlet container calls the request object to delete attributes.

    • Attributereplaced. When the existing property values in the request object are replaced, the servlet container calls the request object.

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 trigger event property, and the getvalue method returns the property value.

Code List 1 shows the sample classes for these two new listeners. When the servlet container calls a method, both display the method name. After the listeners are compiled, their class files must be deployed under the WEB-INF/classes directory. The new method in servletrequest. In servlet 2.4, four new methods are added to the javax. servlet. servletrequest interface:

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

    • Getlocalname. Returns the Host Name of the IP interface from which the request is received.

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

    • Getlocalport. Returns the IP Port Number of the interface from which the request is received.

Note that in servlet 2.3, the values returned by the getservername and getserverport methods are the values returned by the current getlocalname and getlocalport methods. In version 2.4, getservername and getserverport have been redefined. For more information, see the API documentation.

Sample Code on a JSP page as follows --

 
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 the following content:

 
Remote port: 3303 local name: localhost local ADDR: FIG local port: 8080

New features of the Request scheduler. The request scheduler can pass the current request to a new resource or introduce another resource from the current page. Servlet 2.4 adds some attributes that will be added to a request object passed to another resource:

 
Javax. servlet. Forward. Forward

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 resource of the passed object. These attribute values are useful when a resource must be called only through another resource but cannot be called directly.

For example, in a context called MyApp, a servlet named modernservlet is passed to targetservlet. In targetservletCode List 2.

The deployment descriptor of MyApp includes the following: And Element:

<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-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 on the console when modernservlet is called:

 
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 in the request scheduler. Servlet 2.4 adds a new So that the servlet programmer can decide whether to apply the filter to the request scheduler. The element values 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 scheduler Or If the matching Web component uses pass-through call, the filter is used.

    • Include. Only when the request is being processed by the request scheduler Or Filters are used only when matching web components are called with include.

    • Error. Only when the request is processed by the error page mechanism as Filters are used only when elements match wrong resources.

Servlet 2.4 only supports HTTP 1.1 clients. Servlet 2.3 supports both HTTP 1.0 and HTTP 1.1. Unlike servlet 2.4, Servlet 2.3 only supports HTTP 1.1 clients. As a transition, HTTP/1.0 status code 302 (recommended for the moment) 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 302, which is expressed by the static SC _found IN THE httpservletresponse interface.

Servlet is used as a welcome page. In servlet 2.3, you can use Element listing welcome files-the files displayed when an incomplete URL is received. However, in servlet 2.3 Only HTML 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 shows a servlet called modern. Its 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>

In this case, if you type a URL such as http: // domain/Context/(without a source file), modernservlet is called.

New support for internationalization. In servlet 2.3, there is no way to 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 that you must first create a locale object.

In servlet 2.3, you can use the setcontenttype method to pass the content type and character set, for example:

Setcontenttype ('text/html; charset = UTF-8 ');

In servlet 2.4, the javax. servlet. servletresponse interface has two new methods that support internationalization. The first method is setcharacterencoding. Its usage is as follows:

 
Public voidsetcharacterencoding (string charset)

With setcharacterencoding, you can only specify the character encoding as a string without creating a locale object. However, you must call this method before calling the getwriter method and before submitting the response.

The second new method is getcontexttype, which is the result of calling the setcontenttype, setlocale, or setcharacterencoding method in the servletresponse object. It returns the content type 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 makes it unnecessary for servlet programmers to specify locale-to-charset mappings in their/her servlets. 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>

Scalability of deployment descriptors. Verify the deployment descriptor in the servlet 2.3 Application Based on the DTD file. Currently, Servlet 2.4 supports verifying the deployment descriptor according to the mode. The usage mode has the following advantages over the use of DTD:

    • The mode can inherit the syntax of another mode (Extensible.

    • The mode is more accurate than the DTD.

    • You can specify the actual data type of each element in the mode.

    • Mode can be used for multiple namespaces.

    • You can specify the maximum and minimum number of occurrences of an element in the mode.

However, for backward compatibility, the servlet 2.4 container must support servlet 2.3 and Servlet 2.2 DTD.

Javax. servlet. singlethreadmodel interface is not supported. The singlethreadmodel interface does not have a method. It is used to indicate to the servlet container that it must ensure that no two threads execute the servlet service method that implements the interface at the same time. This interface has been widely misunderstood since the emergence of Servlet technology. Everyone is opposed to using it because it can cause chaos and give servlet programmers the illusion of security when considering thread security. This interface should never be used in any new development work.

New features in JSPs 2.0

JSP 2.0 (originally known as JSP 1.3) has an important improvement over JSP 1.2. Of course, the most important content added is the support for Expression Language (EL) added to the JSP 2.0 container.

El was initially defined by the jstl 1.0 specification and can help Delete Java code from the JSP page. The APIS described in the javax. servlet. jsp. El package reveal El semantics. The semantics of El expressions is similar to that of Java expressions. After the expression value is calculated, it is inserted into the current output. El can be used in standard or custom operation attribute values and template text. The following is the structure of the El expression (in which expr is the expression ):

 
$ {Expr}

JSP 2.0 provides a method for changing the text value that contains the Character Sequence "$ {" by using the sequence "$. For example, the following character sequence is converted to a text value $ {expr }:

 
$ {'} Expr}

In addition, since versions earlier than JSP 2.0 do not support El, JSP applications will ignore the El in any web applications. XML is verified based on servlet 2.2 or servlet 2.3 DTD. To test the expressions on the JSP page mentioned here, you only need to delete the Web. xml file from the application.

In fact, El is a simple language that helps page creators access JSP implicit objects, repeated operations and conditional operations that do not contain Java code-these cannot be implemented in JSP 1.2.

To access implicit objects, JSP containers support the following name-object ing:

    • Pagecontext. Pagecontext object

    • Pagination. Map property names in the page range to their values

    • Requestscope. Map property names in the request range to their values

    • Sessionscope. Map attribute names in the session range to their values

    • Applicationscope. Map property names within the application scope to their values

    • Param. Map parameter names to a single string parameter value

    • Paramvalues. Maps parameter names to a string array of all values of this parameter.

    • Header. Map the header name to a single string Header Value

    • Headervalues. Maps the header name to a string array of all values of the header.

    • Cookie. Map cookie names to a single cookie object

    • Initparam. Map the context initialization parameter name to its string parameter value

For example, the following expression indicates the value of username:

$ {Param. Username}

The following expression returns the value of the productid attribute of the session object:

 
$ {Sessionscope. productid}

Simple simpletag interface operation process. JSP 2.0 provides a new interface javax. servlet. jsp. tagext. simpletag, which is a simpler method for compiling 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 the tag processor that implements the tag interface, the most basic situation is that the JSP Container calls the dostarttag and doendtag methods every time it encounters a tag on the JSP page. With JSP 2.0, JSP programmers can use the new simpletag interface to select a simpler tag processor. The JSP Container does not call the two methods of the Tag Processor Implementing the tag interface, but only needs to call a method in the simpletag interface: dotag. This method is used for all tag logic, repeated operations, and subject evaluation. Therefore, simpletag is as powerful as javax. servlet. jsp. tagext. bodytag, but the operation process is simpler.

To support the compilation of the tag processor that needs 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 an execution method: dotag.

Code listing 3 provides an example of a tag processor that extends simpletagsupport.

You can use a Tag file to develop a tag library more easily. As we all know, it takes a lot of time to develop the custom tag library in JSP 1.2. Development involves the development of tag processor and tag library Descriptor (TLD) files, and registration of tag libraries in Web. XML files. JSP 2.0 solves this problem by providing a new method for writing a custom tag library. Using tag files, tag extensions can be similar to JSP files. No need for compilation, no need to edit the Web. xml file, and no need for TLD. All you have to do is copy the markup file to the WEB-INF/tags Directory, which is easy to do. The rest is done by the JSP Container, which converts every Tag file found in the WEB-INF/tags directory to a tag processor. Programmers get rid of the complicated work of building a tag processor.

The following is an example. This is the simplest form of the tag library. The 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 the tag library on the JSP page is much simpler. As usual, you only need to use the taglib command to identify the tag library on the entire page through the prefix attribute. Now you have a tagdir attribute instead of a URI attribute. The tagdir property references any subdirectory under the WEB-INF/tags directory or WEB-INF/tags.

Next step

Read
More about Servlet Technology
Java.sun.com/products/servlet

More about JSP Technology
/Java.sun.com/products/jsp

More about jstl
Otn.oracle.com/oramag/oracle/03-may/o33java.html

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>

The following string is displayed in the browser that calls the JSP page:

Hello from Tag file.

With the expression language mentioned above, you can quickly build a JSP page without scripts. For another example, the following Tag file (example2.tag) receives an attribute by calling the 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); %>

The following is the JSP page that uses the Tag file:

 
<% @ Taglib prefix = "easytag" tagdir = "/WEB-INF/tags" %> <easytag: example2 x = "hello"> </easytag: example2>

The following is another example with 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 on 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, the jstl library is required under the WEB-INF/lib directory.

The last Tag file example also shows that you are not familiar with JavaProgramming LanguagePage creators can still use the powerful feature of tag extension. Even Java programmers are more convenient to use tag files than to write Java classes that implement an interface in the javax. servlet. jsp. tagext package.

Conclusion

This article briefly describes the new features in servlet 2.4 and JSP 2.0 specifications, which will be included in the upcoming J2EE 1.4. Servlet 2.4 and JSP 2.0 will undoubtedly accelerate web application development.

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.