Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

Once again, we use our jhtp6 context root to demonstrate the servlet of Fig. 26.12. Place WelcomeServlet2.html in the servlets directory created in Section 26.4.1. Place WelcomeServlet2.class in the classes subdirectory of WEB-INF in the jhtp6 context root. Remember that classes in a package must be placed in the appropriate package directory structure. Then edit the web.xml deployment descriptor in the WEB-INF directory to include the information specified in Fig. 26.14. This table contains the information for the servlet and servlet-mapping elements that you will add to the web.xml deployment descriptor. You should not type the italic text into the deployment descriptor. Restart Tomcat and type the following URL in your Web browser:

[Page 1256]

[Page 1257]

http://localhost:8080/jhtp6/servlets/WelcomeServlet2.html

Figure 26.14. Deployment descriptor information for servlet

WelcomeServlet2.

(This item is displayed on page 1258 in the print version)

Descriptor element

Value

 

 

servlet element

 

servlet-name

welcome2

description

Handling HTTP get requests with data.

servlet-class

WelcomeServlet2

servlet-mapping element

 

servlet-name

welcome2

url-pattern

/welcome2

 

 

Type your name in the text field of the Web page, then click Submit to invoke the servlet. Once again,

note that the get request could have been typed directly into the browser's Address or Location field as follows:

http://localhost:8080/jhtp6/welcome2?firstname=Jon

[Page 1258]

Error-Prevention Tip 26.4

If an error occurs during the servlet invocation, the log files in the logs directory of the Tomcat installation can help you determine the error and debug the problem.

Software Engineering Observation 26.4

A get request is limited to standard characters, which means that you cannot submit any special characters via a get request. The length of the URL in a get request is limited. For example, the maximum URL length in Internet Explorer is 2,083 characters. Some Web servers might restrict this even more.

Good Programming Practice 26.1

A get request should not be used for sending sensitive data (e.g., a password) because the form data is placed in a query string that is appended to the request URL as plain text and can be intercepted.

[Page 1258 (continued)]

26.6. Handling HTTP post Requests

An HTTP post request is frequently used to send data from an HTML form to a server-side form handler that processes the data. For example, when you respond to a Web-based survey, a post request normally supplies the information you type in the form to the Web server.

Browsers often cache (save on disk) Web pages so they can quickly reload them. If there are no changes between the last version stored in the cache and the current version on the Web, this helps speed up your browsing experience. The browser first asks the server whether the document has changed or expired since the date the file was cached. If not, the browser loads the document from the cache. Thus, the browser minimizes the amount of data that must be downloaded for you to view a Web page. Browsers typically do not cache the server's response to a post request, because the next post might not return the same result. For example, in a survey, many users could visit the same Web page and respond to a question. The survey results could then be displayed for the user. Each new response changes the overall results of the survey.

When you use a Web-based search engine, the browser normally supplies the information you specify in an HTML form to the search engine with a get request. The search engine performs the search, then returns the results to you as a Web page. Such pages are often cached by the browser in case you perform the same search again. As with post requests, get requests can supply parameters as part of the request to the Web server.

[Page 1259]

The WelcomeServlet3 servlet in Fig. 26.15 is identical to the servlet in Fig. 26.12, except that it defines a doPost method (lines 1348) rather than a doGet method to respond to post requests. The default functionality of doPost is to indicate a "Method not supported" error. We override this method to provide custom post request processing. Method doPost accepts the same two arguments as doGetan object that implements interface HttpServletRequest to represent the client's request and an object that implements interface HttpServletResponse to represent the servlet's response. As with doGet, method doPost throws a ServletException if it is unable to handle a client's request and throws an IOException if a problem occurs during stream processing.

Figure 26.15. WelcomeServlet3 responds to a post request containing data.

(This item is displayed on pages 1259 - 1260 in the print version)

1// Fig. 26.15: WelcomeServlet3.java

2// Processing post requests containing data.

3import javax.servlet.ServletException;

4import javax.servlet.http.HttpServlet;

5import javax.servlet.http.HttpServletRequest;

6import javax.servlet.http.HttpServletResponse;

7import java.io.IOException;

8import java.io.PrintWriter;

9

10public class WelcomeServlet3 extends HttpServlet

11{

12// process "post" request from client

13protected void doPost( HttpServletRequest request,

14HttpServletResponse response )

15throws ServletException, IOException

16{

17String firstName = request.getParameter( "firstname" );

19response.setContentType( "text/html" );

20PrintWriter out = response.getWriter();

22// send XHTML page to client

24// start XHTML document

25out.println( "<?xml version = \"1.0\"?>" );

27out.printf( "%s%s%s" , "<!DOCTYPE html PUBLIC" ,

28" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",

29" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );

31out.println( "<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

33// head section of document

34out.println( "<head>" );

35out.println(

36"<title>Processing post requests with data</title>" );

37out.println( "</head>" );

38

39// body section of document

40out.println( "<body>" );

41out.println( "<h1>Hello " + firstName + ",<br />" );

42out.println( "Welcome to Servlets!</h1>" );

43out.println( "</body>" );

44

45// end XHTML document

46out.println( "</html>" );

47out.close(); // close stream to complete the page

48} // end method doPost

49} // end class WelcomeServlet3

[Page 1260]

WelcomeServlet3.html (Fig. 26.16) provides a form (lines 1319) in which the user can input a name in the text input element firstname (line 16), then click the Submit button to invoke WelcomeServlet3. When the user presses the Submit button, the values of the input elements are sent to the server as part of the request. However, note that the values are not appended to the request URL. The form's method in this example is post, but note that a post request cannot be typed into the browser's Address or Location field, and users cannot bookmark post requests in their browsers.

We use our jhtp6 context root to demonstrate the servlet in Fig. 26.15. Place WelcomeServlet3.html in the servlets directory created in Section 26.4.1. Place WelcomeServlet3.class in the classes subdirectory of WEB-INF in the jhtp6 context root. Then, using the information specified in Fig. 26.17, edit the web.xml deployment descriptor in the WEB-INF directory. Restart Tomcat and type the following URL in your Web browser:

[Page 1261]

http://localhost:8080/jhtp6/servlets/WelcomeServlet3.html

Type your name in the text field of the Web page, then click Submit to invoke the servlet.

Figure 26.16. HTML document in which the form's action invokes

WelcomeServlet3 tHRough the alias welcome3 specified in web.xml.

(This item is displayed on pages 1260 - 1261 in the print version)

1

<?xml version = "1.0"?>

2

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

 

5

<!-- Fig. 26.16: WelcomeServlet3.html -->

6

 

7<html xmlns = "http://www.w3.org/1999/xhtml">

8<head>

9<title>Handling an HTTP Post Request with Data</title>

10</head>

11

12<body>

13<form action = "/jhtp6/welcome3" method = "post" >

14<p><label>

15Type your first name and press the Submit button

16<br /><input type = "text" name = "firstname" />

17<input type = "submit" value = "Submit" />

18</label></p>

19</form>

20</body>

21</html>

[View full size image]

Figure 26.17. Deployment descriptor information for servlet

WelcomeServlet3.

Descriptor element

Value

 

 

servlet element

 

servlet-name

welcome3

description

Handling HTTP post requests with data.

 

 

 

 

servlet-class

WelcomeServlet3

servlet-mapping

element

servlet-name

welcome3

url-pattern

/welcome3

 

 

[Page 1261 (continued)]

26.7. Redirecting Requests to Other Resources

Sometimes it is useful to redirect a request to a different resource. For example, a servlet could determine the type of the client browser and redirect the request to a Web page that was designed specifically for that browser. This technique is also used to redirect browsers to an error page when handling a request fails. The RedirectServlet in Fig. 26.18 receives a page parameter as part of a get request, then uses that parameter to redirect the request to a different resource.

[Page 1262]

Figure 26.18. Redirecting requests to other resources.

(This item is displayed on pages 1262 - 1263 in the print version)

1 // Fig. 26.18: RedirectServlet.java

2 // Redirecting a user to a different Web page.

3import javax.servlet.ServletException;

4import javax.servlet.http.HttpServlet;

5import javax.servlet.http.HttpServletRequest;

6import javax.servlet.http.HttpServletResponse;

7import java.io.IOException;

8import java.io.PrintWriter;

9

10public class RedirectServlet extends HttpServlet

11{

12// process "get" request from client

13protected void doGet( HttpServletRequest request,

14HttpServletResponse response )

15throws ServletException, IOException

16{

17String location = request.getParameter( "page" );

19if ( location != null )

20{

21if ( location.equals( "deitel" ) )

22

response.sendRedirect( "http://www.deitel.com" );

23

else if ( location.equals( "welcome1" ) )

24

response.sendRedirect( "welcome1" );

25

} // end if

26

 

27// code that executes only if this servlet

28// does not redirect the user to another page

29response.setContentType( "text/html" );

30PrintWriter out = response.getWriter();

31

32// start XHTML document

33out.println( "<?xml version = \"1.0\"?>" );

35out.printf( "%s%s%s" , "<!DOCTYPE html PUBLIC" ,

36" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",

37" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" );

39out.println(

40"<html xmlns = \"http://www.w3.org/1999/xhtml\">" );

42// head section of document

43out.println( "<head>" );

44out.println( "<title>Invalid page</title>" );

45out.println( "</head>" );

47// body section of document

48out.println( "<body>" );

49out.println( "<h1>Invalid page requested</h1>" );

50out.println( "<p><a href = " +

51"\"servlets/RedirectServlet.html\">" );

52out.println( "Click here to choose again</a></p>" );

53out.println( "</body>" );

54

55// end XHTML document

56out.println( "</html>" );

57 out.close(); // close stream to complete the page

58} // end method doGet

59} // end class RedirectServlet

Line 17 obtains the page parameter from the request. If the value returned is not null, the nested

if... else if statement at lines 2124 determines whether the value is either "deitel" or "welcome1". If the value is "deitel," the response object's sendRedirect method (line 22) redirects the request to www.deitel.com. If the value is "welcome1," line 24 redirects the request to the servlet of Fig. 26.7.

Note that line 24 does not explicitly specify the jhtp6 context root for our Web application. When a servlet uses a relative path to reference another static or dynamic resource, the servlet assumes the same base URL and context root as the one that invoked the servletunless a complete URL is specified for the resource. So line 24 actually is requesting the resource located at

[Page 1263]

http://localhost:8080/jhtp6/welcome1

Similarly, line 51 is actually requesting the resource located at

http://localhost:8080/jhtp6/servlets/RedirectServlet.html

Software Engineering Observation 26.5

Using relative paths to reference resources in the same context root makes your Web application more flexible. For example, you can change the context root without making changes to the static and dynamic resources in the application.

Once method sendRedirect executes, processing of the original request by the RedirectServlet terminates. If method sendRedirect is not called, the remainder of method doGet outputs a Web page indicating that an invalid request was made. The page allows the user to try again by returning to the XHTML document of Fig. 26.19. Note that one of the redirects is sent to a static XHTML Web page and the other is sent to a servlet.

Figure 26.19. RedirectServlet.html document to demonstrate redirecting requests to other resources.

(This item is displayed on page 1264 in the print version)

1

<?xml version = "1.0" ?>

2

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

 

5

<!-- Fig. 26.19: RedirectServlet.html -->

6

 

7<html xmlns = "http://www.w3.org/1999/xhtml">

8<head>

9<title>Redirecting a Request to Another Site</title>

10 </head>

11

12<body>

13<p>Click a link to be redirected to the appropriate page</p>

14<p>

15<a href = "/jhtp6/redirect?page=deitel">

16www.deitel.com</a><br />

17<a href = "/jhtp6/redirect?page=welcome1">

18Welcome servlet</a>

19</p>

20</body>

21</html>

[View full size image]

RedirectServlet.html (Fig. 26.19) provides two links (lines 1516 and 1718) that allow the user to invoke the servlet RedirectServlet. Each link specifies a page parameter as part of the URL. To demonstrate passing an invalid page, you can type the URL into your browser with no value for the page parameter.

We use our jhtp6 context root to demonstrate the servlet of Fig. 26.18. Place RedirectServlet.html in the servlets directory created in Section 26.4.1. Place Redirect-Servlet.class in the classes subdirectory of WEB-INF in the jhtp6 context root. Then, edit the web.xml deployment descriptor in the WEB-INF directory to include the information specified in Fig. 26.20. Restart Tomcat, and type the following URL in your Web browser:

[Page 1264]

http://localhost:8080/jhtp6/servlets/RedirectServlet.html

Click a link in the Web page to invoke the servlet.

Figure 26.20. Deployment descriptor information for servlet

RedirectServlet.

(This item is displayed on page 1265 in the print version)

Descriptor element

Value

 

 

servlet element

 

servlet-name

redirect

description

Redirecting to static Web pages and

 

other servlets.

servlet-class

RedirectServlet

servlet-mapping element

 

servlet-name

redirect

url-pattern

/redirect

 

 

[Page 1265]

When redirecting requests, the request parameters from the original request are passed as parameters to the new request. Additional request parameters can also be passed. For example, the URL passed to sendRedirect could contain name-value pairs. New parameters are added to the existing parameters. A new parameter with the same name as an existing parameter takes precedence over the original value. However, all the values are still passed. In this case, the complete set of values for a given parameter name can be obtained by calling method getParameterValues from interface HttpServletRequest. This method accepts the parameter name as an argument and returns an array of strings containing the parameter values in most-recent-to-least-recent-order.