Java Servlet Technology

Source: Internet
Author: User
Document directory
  • Use scope object
Java Servlet Technology

Stefan bodoff

When the web was used to transmit services at the beginning, the service provider was aware of the need for dynamic content. Applet is the first attempt to achieve this goal. It focuses on using the client platform to deliver dynamic user experience. At the same time, developers are also studying how to use the server platform to achieve this goal. At the beginning, the Common Gateway Interface (CGI) script is the main technology for generating dynamic content. Although widely used, CGI script technology has many defects, including platform relevance and lack of scalability. To avoid these limitations, the Java Servlet technology is born in response to it. It can provide dynamic and user-oriented content in a portable way.

What is Servlet?

A servlet is a class in the Java programming language. It is used to expand the server's performance. The server resides in an application that can be accessed through the "request-response" programming model. Although the servlet can respond to any type of requests, it is generally only used to expand the Web server applications. Java Servlet technology defines an http-specific servlet class for these applications.

The javax. servlet and javax. servlet. Http packages provide interfaces and classes for compiling servlets. All servlets must implement the servlet interface, which defines the lifecycle method.

When implementing a common service, you can use or extend the genericservlet class provided by the Java Servlet API. The httpservlet class provides methods such as doget and dopost to process HTTP-specific services.

This chapter describes how to compile a servlet that responds to an HTTP request. Here we assume that you have learned some basic knowledge about HTTP. If you are not familiar with these protocols, you can have a preliminary understanding of the HTTP protocol from the HTTP overview.

Servlet Example

This chapter describes the tasks related to servlet programming using the Duke's bookstore application. Table 14-1 lists the servlets for each bookstore. Each programming task is described using one or more servlets. For example, bookdetailsservlet describes how to handle http get requests, bookdetailsservlet and catalogservlet show how to build a response, and catalogservlet shows how to track session information.

Table14-1Duke's bookstoreServletExample

Function

Servlet

Go to the bookstore

Bookstoreservlet

Create a bookstore ID

Bannerservlet

Browse the bookstore directory

Catalogservlet

Put books in shopping cart

Catalogservlet,

Bookdetailsservlet

Obtain detailed information about a specific book

Bookdetailsservlet

Show shopping cart

Showcartservlet

Remove one or more books from the shopping cart

Showcartservlet

Buy books in the shopping cart

Cashierservlet

Confirm the purchase

Receiptservlet

The data of these bookstore applications is stored in the database and stored through the help database. bookdb. The database package also includes the bookdetails class. A bookdetails class is used to represent a book. Cart. shoppingcart and cart. shoppingcartitem are used for the shopping cart and shopping cart items respectively.

The source code of the bookstore application is placed in <Jwsdp_home> In the/docs/tutorial/examples/web/bookstore1 directory, this directory is created when the guide package is decompressed.

To build, install, and run this instance, follow these steps:

1. In the terminal window, go to <Jwsdp_home>/Docs/tutorial/examples/web/bookstore1.

2. Run build. The build target will generate any necessary encoding and copy the file directly to <Jwsdp_home>/Docs/tutorial/examples/web/bookstore1/build.

3. Confirm that tomcat has started execution.

4. Run ant install. The Install target notifies Tomcat that a new context is available.

5. Start the database server of pointbase, and still point to the database without full preparation (see accessing the database from Web applications )..

6. Open the bookstore URL http: // localhost: 8080/bookstore1/enter to run the application.

To deploy the application, follow these steps:

1. Run ant package. This package task is to create a war file that contains the application class in the WEB-INF/classes and the context. xml file in the META-INF.

2. Confirm that tomcat has started execution.

3. Run ant deploy. The deploy target copies the war to Tomcat, and the notification has a new context.

Troubleshooting

The general problems and solutions list the reasons why the Web Client fails. In addition, the Duke bookstore returns the following exception:

· Booknotfoundexception -- this exception is returned if a book cannot be found in the database of the bookstore. This exception occurs if the user does not run ant create-book-dB to load data in the bookstore database, or the database server is not running, or the database has crashed.

· Booksnotfoundexception -- this exception is returned if the data in the bookstore cannot be obtained. This exception occurs if the user does not run ant create-book-dB to load data in the bookstore database, or the database server is not running, or the database has crashed.

· Unavailableexception -- this exception is returned if the servlet cannot obtain the web context attribute used to represent the bookstore. If you do not copy the client library pointing to (pointbase) <Pb_home>/Lib/pbclient45.jar to <Jwsdp_home>/Common/lib, or if the point to (piontbase) server is not running, or the user does not define tomcat to reference the data source pointing to the database (pointbase), this exception occurs.

Because an error page is specified, the user will see the application is unavailable. please try later. if a correct page is specified, the Web Container will generate a response page containing the servlet exception has occurred message and a stack to help diagnose the cause of the exception. If you use errorpage.html, you can understand the logs that the Web Container determines the cause of the exception. The web log is located in <Jwsdp_home>/In the logs directory, the logs are sdp_log. <Date>. Txt.

Servlet Lifecycle

The lifecycle of a servlet is controlled by the servlet container. When a request is mapped to a servlet, the container performs the following steps.

1. If a servlet instance does not exist, the Web Container

A. Load the servlet class.

B. Create a servlet class instance.

C. Call init to initialize the servlet instance. The initialization process will be described in the initialization servlet.

2. Call the service method to pass a request and response object. The service method will be described in writing the service method.

If the container wants to remove the servlet, you can call the destroy method of the servlet to end the servlet. The End Process will be discussed in the end Serlvet.

Process servlet lifecycle events

In the servlet lifecycle, you can detect and respond to events by defining the listener object. When a lifecycle event occurs, call the method of the object. To use these listener objects, you must define the listener class and specify the corresponding listener class.

Define listener class

You can define the listener class as an implementation of the listener interface. Servlet lifecycle events list events that can be detected and corresponding required interfaces. When you call a listener method, you must pass an event that contains the appropriate event information to the method. For example, an httpsessionevent event is passed to the methods in the httpsessionlistener interface. This event contains an httpsession.

Table 14-2 servleLifecycle events

Object

Event

Listener interface and event class

Web Context
(See access web context)

Initialization and destruction

Javax. servlet.
Servletcontextlistener and

Servletcontextevent

Add, delete, or replace an attribute

Javax. servlet.
Servletcontextattributelistener and

Servletcontextattributeevent

Session
(See maintaining the customer's delivery status)

Creation, failure, and timeout

Javax. servlet. HTTP.
Httpsessionlistener and

Httpsessionevent

Add, delete, or replace an attribute

Javax. servlet. HTTP.
Httpsessionattributelistener and

Httpsessionbindingevent

The listeners. contextlistener class is used to create and remove Database Assistants and counter objects used in the Duke bookstore application. Method to obtain the web context object from servletcontextevent, and then store (and remove) the object as the servlet context attribute.

Import database. bookdb;
Import javax. servlet .*;
Import util. counter;

Public final class contextlistener
Implements servletcontextlistener {
Private servletcontext context = NULL;
Public void contextinitialized (servletcontextevent event ){
Context = event. getservletcontext ();
Try {
Bookdb = new bookdb ();
Context. setattribute ("bookdb", bookdb );
} Catch (exception ex ){
System. Out. println (
"Couldn't create database :"
+ Ex. getmessage ());
}
Counter = new counter ();
Context. setattribute ("hitcounter", counter );
Context. Log ("created hitcounter"
+ Counter. getcounter ());
Counter = new counter ();
Context. setattribute ("ordercounter", counter );
Context. Log ("created ordercounter"
+ Counter. getcounter ());
}

Public void contextdestroyed (servletcontextevent event ){
Context = event. getservletcontext ();
Bookdb = context. getattribute (
"Bookdb ");
Bookdb. Remove ();
Context. removeattribute ("bookdb ");
Context. removeattribute ("hitcounter ");
Context. removeattribute ("ordercounter ");
}
}

Specify the event listener class

To specify an event listener class, you must add a listener element to the Web application deployment descriptor. The following is a listener element of the duke bookstore application.

<Listener>
<Listener-class> listeners. contextlistener </listener-class>
</Listener>

Handling error

Many exceptions may occur when the servlet is executed. When an exception occurs, the Web Container generates a default page containing the servlet exception has occurred message. However, you can also return a container that contains the error page specified for a given exception. To specify such a page, you need to add an error-page element to the deployment descriptor of the Web application. In this case, the dukestore APP returns an exception to errorpage.html:

<Error-page>
<Exception-type>
Exception. booknotfoundexception
</Exception-type>
<Location>/errorpage.html </location>
</Error-page>
<Error-page>
<Exception-type>
Exception. booksnotfoundexception
</Exception-type>
<Location>/errorpage.html </location>
</Error-page>
<Error-page>
<Exception-type> exception. orderexception </exception-type>
<Location>/errorpage.html </location> </error-page>

Share information

Like most objects, Web components usually work with other objects to complete tasks. There are multiple methods to achieve this. Web components can use private helper (helper) objects (for example, JavaBeans components) or share objects with common scope attributes. They can use databases, you can also call other web resources. The Java Servlet technical mechanism allows a Web component to call other web resources, which is described in calling other web resources.

Use scope object

Several collaborative Web Components share information through some objects, which are maintained as attributes of the four scope objects. These attributes can be accessed through the [GET | set] attribute method that represents the domain class. Table 14-3 lists the scope objects.

Table 14-3Scope object

Scope object

Class

Which components can be accessed?

Web Context

Javax. servlet.
Servletcontext

Web Components in the web context. See access web context

Session

Javax. servlet.
HTTP. httpsession

A Web component that processes a session request. See maintain the client status.

Request

Javax. servlet.
Servletrequest

Child type

The Web component that processes the request.

Page

Javax. servlet.
JSP. pagecontext

Create a JSP page for the object. See implicit object.

Figure 14-1 shows the scope attributes maintained by the Duke bookstore application.

Figure 14-1DukeBookstore scope attributes

Control concurrent access to shared resources

Concurrent access to shared resources may occur on a multi-threaded server. In addition to the scope object attributes, shared resources also include data in memory (such as instances and class variables), external objects (such as files), database connections, and network connections. Concurrent access can appear in multiple cases.

· Multiple Web Components access objects stored in the web context. T

· Multiple Web Components access objects stored in sessions.

· Multiple Threads in a Web Component Access instance variables. A Web Container generally creates a thread for each request for processing. If you confirm that a servlet instance processes only one request at a time, the servlet can implement the singlethreadmodel interface. If the servlet implements this interface, the user can ensure that the servlet service method cannot have two threads for concurrent execution. Web containers can be implemented by synchronously accessing a single servlet instance, or by maintaining a Web component pool to call a new request for each instance. This interface does not prevent synchronization problems caused by Web Components accessing shared resources (such as static class variables and external objects ).

When resources can be accessed concurrently, you can use inconsistent resources. To prevent this situation, you mustJava GuideThe synchronous mechanism described in the thread unit in to control access.

In the previous sections, we described the five scope attributes shared by multiple servlets: bookdb, cart, currency, hitcounter, and ordercounter. The bookdb attributes will be discussed in the next section. Cart, currency, and counter can be set and read by multi-threaded servlets. Use the synchronization method to control access to prevent inconsistent use of these objects. For example, the following is an util. Counter class:

Public class counter {
Private int counter;
Public counter (){
Counter = 0;
}
Public synchronized int getcounter (){
Return counter ;}
Public synchronized int setcounter (INT c ){
Counter = C; return counter;
}
Public synchronized int inccounter (){
Return (++ counter );
}
}

Access Database

Data shared between Web Components and maintained between calls to a web application is usually maintained by a database. Web Components use JDBC 2.0 APIs to access relational databases. The data of the bookstore application is maintained by the database and accessed through the assistant database. bookdb. For example, after a user buys a book, receiptservlet calls the bookdb. buybooks method to update the book list. The buybooks method calls buybook for every book contained in the shopping cart. To ensure that the command is fully executed, the calling program of the buybook will be packaged in a separate JDBC transaction. You can use the [GET | release] connection method to synchronize the shared database connection.

Public void buybooks (shoppingcart cart) throws orderexception {
Collection Items = cart. getitems ();
Iterator I = items. iterator ();
Try {
Getconnection ();
Con. setautocommit (false );
While (I. hasnext ()){
Shoppingcartitem Sci = (shoppingcartitem) I. Next ();
Bookdetails BD = (bookdetails) Sci. getitem ();
String id = BD. getbookid ();
Int quantity = Sci. getquantity ();
Buybook (ID, quantity );
}
Con. Commit ();
Con. setautocommit (true );
Releaseconnection ();
} Catch (exception ex ){
Try {
Con. rollback ();
Releaseconnection ();
Throw new orderexception ("transaction failed:" +
Ex. getmessage ());
} Catch (sqlexception sqx ){
Releaseconnection ();
Throw new orderexception ("rollback failed:" +
Sqx. getmessage ());
}
}
}

Initialization Servlet

After the Web container loads and instantiates the servlet class and the servlet instance passes requests from the client, the Web Container initializes the servlet. You can customize this initialization process to allow the servlet to read persistent configuration data, initialize resources, and ignore the init method of the servlet interface to execute any other one-time activities. Servlet must use unavailableexception to complete the initialization process.

All servlets (bookstoreservlet, catalogservlet, bookdetailsservlet, andShowcartservlet)Initialize a variable in their init method to point to the Database Assistant object created with the web context listener.

Public class catalogservlet extends httpservlet {
Private bookdb;
Public void Init () throws servletexception {
Bookdb = (bookdb) getservletcontext ().
Getattribute ("bookdb ");
If (bookdb = NULL) throw new
Unavailableexception ("couldn't get database .");
}
}

Write service methods

The service provided by Servlet is implemented in the service method of genericservlet, do of httpservletMethodMethod (in this method,MethodCan contain get, delete, options, post, put, trace values), or any other protocol specified by the class definition that implements the servlet interface (protocol-specific). In the rest of this chapter, the term "service method" is used to define any method in a servlet class that provides services to the client.

The general mode of a service method is to extract information from a request, access external resources, and fill in the response based on the information.

For httpservlet, the correct process of filling the response is: first fill the response header, then get an output stream from the response, and finally write all the main content of the output stream. The Response Header must be set before printwriter or servletoutputstream is obtained, because the HTTP protocol wants to obtain information about all headers before the body content. The next two sections describe how to obtain information from the request and generate a response.

Obtain information from the request

A request contains data transmitted between the client and servlet. All requests implement the servletrequest interface, which defines the method for accessing the information:

· Parameters, usually used to transmit information between the client and Servlet

· Object-valued attribute, which is usually used to transmit information between the servlet container and the servlet or between the servlet that is collaborating

· Information about protocols used for communication between requests, clients, and servers involved in the request.

· Information about regionalization.

For example, in catalogservlet, the identifier of the book that the customer wants to purchase is included as a parameter in the request. The following code illustrates how to use the getparameter method to extract an identifier.

String bookid = request. getparameter ("add ");
If (bookid! = NULL ){
Bookdetails book = bookdb. getbookdetails (bookid );

You can also obtain an input stream from the request and manually parse the data. To read character data, you can use the bufferedreader object returned by the getreader method of the request. To read binary data, you can use the servletinputstream returned by getinputstream.

HTTP Serlvet is transmitted through the HTTP request object. httpservletrequest includes the request URL, HTTP header, and query string.

An HTTP request URL contains the following parts:

Http: // [host]: [port] [Request Path]? [Query string]

The request path consists of the following elements:

·Context path:Splice forward slash/with the context root of the servlet web application.

·ServletPath: The Path corresponding to the component alias that activates the request, starting with the forward slash.

·Path information: The part of the Request Path, not the context path or Servlet Path.

If the context path is an alias in the/catalog and column 14-4 of the table, table 14-5 provides some examples to illustrate how to break down the URL.

Table 14-4Alias

Mode

Servlet

/Lawn /*

Lawnservlet

/*. Jsp

Jspservlet

Table14-5Request Path Element

Request Path

ServletPath

Path information

/CATALOG/lawn/index.html

/Lawn

/Index.html

/CATALOG/help/feedback. jsp

/Help/feedback. jsp

Null

A query string consists of a set of parameters and values. Each parameter is obtained by using the getparameter method in the request. There are two methods to generate a query string:

· A query string can be explicitly displayed on the web page. For example, an HTML page is generated by catalogservlet and contains <a href = "/bookstore1/catalog? Add = 101 "> Add to cart </a>. Catalogservlet puts forward the parameter named "add" as follows:

String bookid = request. getparameter ("add ");

· When a form is submitted together with a get http method, a query string is appended to the URL. In the Duke bookstore application, cashierservlet first generates a form, and then enters a username in the form, which is appended to the URL mapped to receiptservlet, finally, receiptservlet uses the getparameter method to extract the user name.

 

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.