Passing Parameter Data to a Servlet

Your first servlet, although it shows the principle of servlets, was not actually a very good servlet example. As you have probably realized, it could have been written as a static HTML page and you could have avoided all the complication of having to compile and deploy a servlet. The next example will show the power of servlets.

How to Access Parameters

The power of servlets comes into its own when the data is dynamic. Dynamic data can come from many sources. It can be obtained from an external resource (such as a file, database, or another Web page) or it can be sent from a HTML form to the server in the form of parameters.

Parameters are name-value pairs. Parameters are defined in the HTML, for example

<INPUT TYPE=TEXT NAME="myname">

places an input text box on the page and any data typed in the input box is associated with a parameter called myname.

If the form uses a GET method, this parameter will be added to the URL as part of the query string, as in the following:

http://localhost:8000/Servlets/example?myname=Rupert

In the servlet, you use the HttpServletRequest.getParameter() method to gain access to parameters. For example, the following line will obtain the value stored in the myname parameter:

String name = req.getParameter("myname");

Servlet Example with Parameters

Youwill now code an application takes information from a simple form and displays it back to the user. There are two parts to the application:

  • VerifyForm A static HTML form that obtains the data from the user (shown in Listing 12.6).

  • VerifyData A servlet that simply sends the entered data back to the client (shown in Listing 12.7). This is actually quite a common requirement, where the user is presented with the data just typed into a form to visually verify it before the application continues processing it.

If you deploy the form, VerifyForm, as part of your Web application, you can use a relative path to access the servlet "/Servlets/VerifyData" (line 4 of Listing 12.6). Otherwise, you will need the full path "http://localhost:8000/Servlets/VerifyData".

Listing 12.6. VerifyForm HTML Page to Obtain the Data
 1: <HTML>
 2:   <HEAD><TITLE>Verify Form</TITLE></HEAD>
 3:   <BODY>
 4:     <FORM METHOD=GET ACTION="/Servlets/VerifyData">
 5:       <P>Please type in your details:</P>
 6:       Name:
 7:       <INPUT TYPE=TEXT NAME="name">
 8:       Telephone No:
 9:       <INPUT TYPE=TEXT NAME="tel">
10:       <P>Click on Submit when done</P>
11:       <INPUT TYPE=SUBMIT>
12:     </FORM>
13:   </BODY>
14: </HTML>
						

When you click the Submit Query button, the text typed in the two input boxes is sent as a query string to the servlet. The query string is appended at the end of the URL that was specified as the ACTION attribute (line 4 in Listing 12.6) to the form, as shown in the following:

http://localhost:8000/Servlets/VerifyData?name=Rupert+&tel=123456789

The VerifyData servlet (shown in full in Listing 12.7) uses the getParameter() method to access these parameters. Deploy this servlet as part of your Servlets application.

Listing 12.7. VerifyData Servlet with Parameters
 1: import java.io.*;
 2: import javax.servlet.*;
 3: import javax.servlet.http.*;
 4:
 5: public class VerifyData extends HttpServlet {
 6:
 7:     public void doGet(HttpServletRequest req, HttpServletResponse res)
 8:                  throws IOException {
 9:         res.setContentType ("text/html");
10:         PrintWriter out = res.getWriter();
11:         String name = req.getParameter("name");
12:         String tel = req.getParameter("tel");
13:         out.println ("<HTML>");
14:         out.println ("<HEAD><TITLE>Verify Data</TITLE></HEAD>");
15:         out.println ("<BODY>");
16:         out.println ("<H1>Hello " + name + " " + tel + "</H1>");
17:         out.println ("</BODY>");
18:         out.println ("</HTML>");
19:     }
20: }
						

If everything is correct and you have typed in the data in Figure 12.12, this servlet produces the output shown in Figure 12.13.

Figure 12.12. VerifyForm page.


Figure 12.13. VerifyData page.


Using a POST Request

As already discussed, both the HTTP methods POST and GET can be used to send data to a servlet. Generally, you need the functionality to be the same if either GET or POST is used.

The simplest way for a servlet to handle POST requests is to dispatch the request to the doGet() method. Add the following doPost() method to your servlet:

public void doPost(HttpServletRequest req, HttpServletResponse res)
                 throws ServletException, IOException {
    doGet (req, res);
}

Now change your form to use POST instead of GET. To do this, change line 4 of Listing 12.6 to the following:

<FORM METHOD=POST ACTION="/Servlets/VerifyData">

You will notice that the parameters are not included as part of the URL this time, but the output and the effect is exactly the same as when GET was used.

The Servlet Lifecycle

The servlet specification defines the lifecycle of a servlet, this is shown in Figure 12.14, and the servlet container's responsibilities. The server is responsible for loading, instantiating, and initializing servlets. But exactly when this happens is not defined, a server may instantiate all servlets when the servlet engine is started, or instantiation of a servlet may be delayed until it is needed. The lifespan of a servlet is also non-deterministic. A server may keep a servlet active for a long time, or the server may remove a servlet when resources are low.

Figure 12.14. Lifecycle of a servlet.


When a servlet is instantiated, the server calls the servlet's init() method. This is called once and once only, and should be used to set up servlet resources and initialize servlet instance variables. A servlet can access its context in the init() method.

The init() method must complete before the servlet can service any requests. The servlet will not be put into service if the init() method throws a ServletException.

The init() method is defined in the superclass. You only need override this method if you need to do some initialization for the servlet.

The destroy() method is called by the server when the servlet is removed from service. Because a server can destroy a servlet at any time, it should be used not only to free resources but also to save any data or state information that may be required when the servlet is called again. After a servlet has been initialized, request and response objects are passed as parameters to the appropriate doXXX() method (see Figure 12.15) of the servlet interface.

Figure 12.15. Sequence diagram of HTTP GET and POST requests.


These objects are as follows:

  • javax.servlet.http.HttpServletRequest

  • javax.servlet.http.HttpServletResponse

The Servlet Context

The javax.servlet.ServletContext interface provides a set of methods that the servlet can use to communicate with the Web server. The ServletContext object is contained within the javax.servlet.ServletConfig object, which is provided to the servlet when it is first initialized.

Using the ServletContext object, a servlet can perform the following functions:

  • Set and store attributes that other servlets in the context can access.

  • Log events.

  • Obtain URL references to resources.

  • Get values assigned to initialization parameters. These are parameters associated with a servlet, not an individual request.

  • Get the MIME type of files.

  • Obtain information about the servlet container, such as its name and version.

A servlet context is associated with a Web application and shared by all the servlets within that application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.151