Presentation is loading. Please wait.

Presentation is loading. Please wait.

Servlets Outline Introduction Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle HttpServlet Class HttpServletRequest.

Similar presentations


Presentation on theme: "Servlets Outline Introduction Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle HttpServlet Class HttpServletRequest."— Presentation transcript:

1 Servlets Outline Introduction Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle HttpServlet Class HttpServletRequest Interface HttpServletResponse Interface Handling HTTP get Requests Deploying a Web Application Handling HTTP get Requests Containing Data Handling HTTP post Requests Redirecting Requests to Other Resources Multi-Tier Applications: Using JDBC from a Servlet

2 Introduction Java networking capabilities (develop Internet-based and Web-based applications) Fundamental networking capabilities -- Package java.net Socket-based communications (used for text) Packet-based communications (used for audio/video) Client-server relationship Client requests action to be performed Server performs action and responds to client Servlet extends functionality of (Web) server

3 Java networking capabilities
Introduction Java networking capabilities Servlets and Java Server Pages (JSP) Request-response model Packages javax.servlet (servlets) javax.servlet.http (servlets) javax.servlet.jsp (JSPs) javax.servlet.tagext (JSPs) Servlets – Web-based solutions Secure access to Website Interact with databases Dynamically generate custom HTML documents JSPs provide some of same functionality without getting into details of servlets

4 Servlet Overview and Architecture
Servlets used when small portion of content sent to client is static Java Server Pages (JSPs) used when only small portion of content set to client is dynamic, most is static HyperText Transfer Protocol (HTTP) Uniform Resource Locator (URL) Servlets communicate between clients and servers using HTTP

5 Servlet Overview and Architecture
Client sends HTTP request Servlet container receives request, directs it to the appropriate servlet Servlet does processing (including interacting with databases) Servlet returns results to client in form of HTML document

6 Interface Servlet and the Servlet Life Cycle
All servlets must implement this interface All methods of interface Servlet are invoked by servlet container Servlet life cycle Servlet container invokes the servlet’s init method before servlet can respond to first request Servlet’s service method handles requests (receives, processes, sends response to client) Servlet’s service method called once per request, runs in a Thread Servlet’s destroy method releases servlet resources when the servlet container terminates the servlet

7 Interface Servlet and the Servlet Life Cycle
Servlet implementation (two abstract classes implement Servlet interface) GenericServlet (javax.servlet) HttpServlet (javax.servlet.http) service method ServletRequest object is data from client ServletResponse object is data to the client

8 Interface Servlet and the Servlet Life Cycle (Cont.)

9 Web-based servlets typically extend class HttpServlet
HttpServlet overrides method service Two most common HTTP request types get requests (data rides on URL) post requests (data sent in a file) Method doGet responds to get requests Method doPost responds to post requests

10 HttpServlet Class HttpServletRequest and HttpServletResponse objects enable interaction between client and server

11 HttpServletRequest Interface
Web server creates an HttpServletRequest object passes it to the servlet’s service method (that is, doGet or doPost) HttpServletRequest object contains the request from the client

12 HttpServletRequest Interface (Cont.)

13 HttpServletResponse Interface
Web server creates an HttpServletResponse object passes it to the servlet’s service method (that is, doGet or doPost)

14 HttpServletResponse Interface (Cont.)

15 Handling HTTP get Requests
May send data on the URL; this example does not Example: WelcomeServlet a servlet handles HTTP get requests response.setContentType("text/html") provides the browser with Multipurpose Internet Mail Extension (MIME) type

16 Import the javax.servlet and javax.servlet.http packages.
// Fig. 24.5: WelcomeServlet.java // A simple servlet to process get requests. 3 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; 7 public class WelcomeServlet extends HttpServlet { 9 // process "get" requests from clients protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 17 // send XHTML page to client 19 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 22 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 26 Import the javax.servlet and javax.servlet.http packages. WelcomeServlet Lines 4-5 Line 8 Lines Line 15 Line 16 Lines 21-40 Extends HttpServlet to handle HTTP get requests and HTTP post requests. Override method doGet to provide custom get request processing. Uses the response object’s setContentType method to specify the content type of the data to be sent as the response to the client. Uses the response object’s getWriter method to obtain a reference to the PrintWriter object that enables the servlet to send content to the client. Create the XHTML document by writing strings with the out object’s println method.

17 27 out. println( "<html xmlns = \"http://www. w3
28 // head section of document out.println( "<head>" ); out.println( "<title>A Simple Servlet Example</title>" ); out.println( "</head>" ); 33 // body section of document out.println( "<body>" ); out.println( "<h1>Welcome to Servlets!</h1>" ); out.println( "</body>" ); 38 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 43 } WelcomeServlet Line 41 Closes the output stream, flushes the output buffer and sends the information to the client.

18 WelcomeServlet.html 1 <?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig. 24.6: WelcomeServlet.html --> 6 <html xmlns = " <head> <title>Handling an HTTP Get Request</title> 10 </head> 11 12 <body> <form action = "/jhtp5/welcome1" method = "get"> 14 <p><label>Click the button to invoke the servlet <input type = "submit" value = "Get HTML Document" /> </label></p> 18 </form> 20 </body> 21 </html> WelcomeServlet.html

19 Program output

20 Deploying a Web Application
Web applications JSPs, servlets, and their supporting files Deploying a Web application Deployment descriptor web.xml

21 Element servlet describes a servlet.
<!DOCTYPE web-app PUBLIC \ "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" " 4 <web-app> 6 <!-- General description of your Web application --> <display-name> Java How to Program JSP and Servlet Chapter Examples </display-name> 12 <description> This is the Web application in which we demonstrate our JSP and Servlet examples. </description> 17 <!-- Servlet definitions --> <servlet> <servlet-name>welcome1</servlet-name> 21 <description> A simple servlet that handles an HTTP get request. </description> 25 web.xml Lines Lines Lines Lines Line 20 Lines Lines 26-28 Element web-app defines the configuration of each servlet in the Web application and the servlet mapping for each servlet. Element display-name specifies a name that can be displayed to the administrator of the server on which the Web application is installed. Element description specifies a description of the Web application that might be displayed to the administrator of the server. Element servlet describes a servlet. Element servlet-name is the name for the servlet. Element description specifies a description for this particular servlet.

22 Element servlet-class specifies compiled servlet’s fully qualified class name.
WelcomeServlet </servlet-class> </servlet> 30 <!-- Servlet mappings --> <servlet-mapping> <servlet-name>welcome1</servlet-name> <url-pattern>/welcome1</url-pattern> </servlet-mapping> 36 37 </web-app> web.xml Lines Lines 32-35 Element servlet-mapping specifies servlet-name and url-pattern elements.

23 Handling HTTP get Requests Containing Data
Servlet WelcomeServlet2 Responds to a get request that contains data Parameters passed as name/value pairs on the URL ( String firstName = request.getParameter("firstname"); retrieves the string “Paul” retrieves null if no parameter has the name firstname parameters typically come from HTML FORMs servlet is called when SUBMIT button is clicked Multiple parameters separated by &’s (

24 WelcomeServlet2 responds to a get request that contains data. Line 15
// Fig : WelcomeServlet2.java // Processing HTTP get requests containing data. 3 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; 7 public class WelcomeServlet2 extends HttpServlet { 9 // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); 16 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 19 // send XHTML document to client 21 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 24 WelcomeServlet2 responds to a get request that contains data. Line 15 The request object’s getParameter method receives the parameter name and returns the corresponding String value.

25 WelcomeServlet2 responds to a get request that contains data. Line 39
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 28 out.println( "<html xmlns = \" ); 30 // head section of document out.println( "<head>" ); out.println( "<title>Processing get requests with data</title>" ); out.println( "</head>" ); 36 // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); 42 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 47 } WelcomeServlet2 responds to a get request that contains data. Line 39 Uses the result of line 16 as part of the response to the client.

26 Get the first name from the user.
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig : WelcomeServlet2.html --> 6 <html xmlns = " <head> <title>Processing get requests with data</title> 10 </head> 11 12 <body> <form action = "/jhtp5/welcome2" method = "get"> 14 <p><label> Type your first name and press the Submit button <br /><input type = "text" name = "firstname" /> <input type = "submit" value = "Submit" /> </p></label> 20 </form> 22 </body> 23 </html> HTML document in which the form’s action invokes WelcomeServlet2 through the alias welcome2 specified in web.xml. Line 17 Get the first name from the user.

27 HTML document in which the form’s action invokes WelcomeServlet2 through the alias welcome2 specified in web.xml. Program output

28 Handling HTTP post Requests
Post data from an HTML form to a server-side form handler using a file Browsers usually do NOT cache post requests Search engines usually use “get” because just a little data Browsers usually cache get requests Servlet WelcomeServlet3 Responds to a post request that contains data

29 Declare a doPost method to responds to post requests.
// Fig : WelcomeServlet3.java // Processing post requests containing data. 3 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; 7 public class WelcomeServlet3 extends HttpServlet { 9 // process "post" request from client protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String firstName = request.getParameter( "firstname" ); 16 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 19 // send XHTML page to client 21 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 24 WelcomeServlet3 responds to a post request that contains data. Lines 11-46 Declare a doPost method to responds to post requests.

30 25 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 28 out.println( "<html xmlns = \" ); 30 // head section of document out.println( "<head>" ); out.println( "<title>Processing post requests with data</title>" ); out.println( "</head>" ); 36 // body section of document out.println( "<body>" ); out.println( "<h1>Hello " + firstName + ",<br />" ); out.println( "Welcome to Servlets!</h1>" ); out.println( "</body>" ); 42 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 47 } WelcomeServlet3.java

31 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig : WelcomeServlet3.html --> 6 <html xmlns = " <head> <title>Handling an HTTP Post Request with Data</title> 10 </head> 11 12 <body> <form action = "/jhtp5/welcome3" method = "post"> 14 <p><label> Type your first name and press the Submit button <br /><input type = "text" name = "firstname" /> <input type = "submit" value = "Submit" /> </label></p> 20 </form> 22 </body> 23 </html> HTML document in which the form’s action invokes WelcomeServlet3 through the alias welcome3 specified in web.xml. Lines 13-21 Provide a form in which the user can input a name in the text input element firstname, then click the Submit button to invoke WelcomeServlet3.

32 HTML document in which the form’s action invokes WelcomeServlet3 through the alias welcome3 specified in web.xml. Program output

33 Redirecting Requests to Other Resources
Servlet RedirectServlet Redirects the request to a different resource Why not just have links to those resources? Could determine browser type and choose link accordingly Could add parameters before redirecting (those sent originally are included automatically) response.sendRedirect(URL); redirects to that URL immediately terminates current program Use relative paths whenever possible to make Website portable

34 Obtains the page parameter from the request.
// Fig : RedirectServlet.java // Redirecting a user to a different Web page. 3 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; 7 public class RedirectServlet extends HttpServlet { 9 // process "get" request from client protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String location = request.getParameter( "page" ); 16 if ( location != null ) 18 if ( location.equals( "deitel" ) ) response.sendRedirect( " ); else if ( location.equals( "welcome1" ) ) response.sendRedirect( "welcome1" ); 24 RedirectServletredirecting requests to other resources. Line 15 Lines Line 20 Line 23 Lines 29-56 Obtains the page parameter from the request. Determine if the value is either “deitel” or “welcome1” Redirects the request to Redirects the request to the servlet WelcomeServlet.

35 RedirectServletredirecting requests to other resources. Lines 28-55
// code that executes only if this servlet // does not redirect the user to another page 27 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); 30 // start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 33 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 37 out.println( "<html xmlns = \" ); 40 // head section of document out.println( "<head>" ); out.println( "<title>Invalid page</title>" ); out.println( "</head>" ); 45 // body section of document out.println( "<body>" ); out.println( "<h1>Invalid page requested</h1>" ); Output a Web page indicating that an invalid request was made if method sendRedirect is not called. RedirectServletredirecting requests to other resources. Lines 28-55

36 RedirectServletredirecting requests to other resources.
out.println( "<p><a href = " + "\"servlets/RedirectServlet.html\">" ); out.println( "Click here to choose again</a></p>" ); out.println( "</body>" ); 53 // end XHTML document out.println( "</html>" ); out.close(); // close stream to complete the page } 58 } RedirectServletredirecting requests to other resources.

37 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig : RedirectServlet.html --> 6 <html xmlns = " <head> <title>Redirecting a Request to Another Site</title> 10 </head> 11 12 <body> <p>Click a link to be redirected to the appropriate page</p> <p> <a href = "/jhtp5/redirect?page=deitel"> /> <a href = "/jhtp5/redirect?page=welcome1"> Welcome servlet</a> </p> 20 </body> 21 </html> RedirectServlet.html document to demonstrate redirecting requests to other resources. Lines Lines 17-18 Provide hyperlinks that allow the user to invoke the servlet RedirectServlet.

38 RedirectServlet.html document to demonstrate redirecting requests to other resources. Program output

39 Multi-Tier Applications: Using JDBC from a Servlet
Servlets can communicate with databases via JDBC Three-tier distributed applications User interface Processing logic Database access HTML user interface makes interface very accessible across multiple platforms Web servers often represent the middle tier

40 24.7 Multi-Tier Applications: Using JDBC from a Servlet
Three-tier distributed application example Survey.html SurveyServlet Cloudscape database Method init called once in servlet’s lifetime public void init(ServletConfig config) ServletConfig object supplies information from web.xml deployment descriptor file config.getInitParameter (”databaseLocation") gets value of databaseLocation parameter from web.xml

41 Servlets are initialized by overriding method init.
// Fig. 24.20: SurveyServlet.java // A Web-based survey that uses JDBC from a servlet. package com.deitel.jhtp5.servlets; 4 import java.io.*; import java.text.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; 10 11 public class SurveyServlet extends HttpServlet { private Connection connection; private Statement statement; 14 // set up database connection and create SQL statement public void init( ServletConfig config ) throws ServletException { // attempt database connection and create Statements try { System.setProperty( "db2j.system.home", config.getInitParameter( "databaseLocation" ) ); 22 Class.forName( config.getInitParameter( "databaseDriver" ) ); connection = DriverManager.getConnection( config.getInitParameter( "databaseName" ) ); SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Lines Lines Line 23 Lines Lines 27-31 Servlets are initialized by overriding method init. Specify database location Loads the database driver. Attempt to open a connection to the animalsurvey database.

42 Create Statement to query database.
26 // create Statement to query database statement = connection.createStatement(); } 30 // for any exception throw an UnavailableException to // indicate that the servlet is not currently available catch ( Exception exception ) { exception.printStackTrace(); throw new UnavailableException(exception.getMessage()); } 37 } // end of init method 39 // process survey response protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { // set up response to client response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); DecimalFormat twoDigits = new DecimalFormat( "0.00" ); 49 Create Statement to query database. SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Line 28

43 Obtain the survey response
// start XHTML document out.println( "<?xml version = \"1.0\"?>" ); 52 out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " + "XHTML 1.0 Strict//EN\" \" + "/TR/xhtml1/DTD/xhtml1-strict.dtd\">" ); 56 out.println( "<html xmlns = \" ); 59 // head section of document out.println( "<head>" ); 62 // read current survey response int value = Integer.parseInt( request.getParameter( "animal" ) ); String query; 67 // attempt to process a vote and display current results try { 70 // update total for current surevy response query = "UPDATE surveyresults SET votes = votes + 1 " + "WHERE id = " + value; statement.executeUpdate( query ); 75 SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Lines Lines Line 74 Obtain the survey response Create query to update total for current survey response Execute query to update total for current survey response

44 Create query to get total of all survey responses
query = "SELECT sum( votes ) FROM surveyresults"; ResultSet totalRS = statement.executeQuery( query ); totalRS.next(); int total = totalRS.getInt( 1 ); 81 // get results query = "SELECT surveyoption, votes, id FROM surveyresults " + "ORDER BY id"; ResultSet resultsRS = statement.executeQuery( query ); out.println( "<title>Thank you!</title>" ); out.println( "</head>" ); 88 out.println( "<body>" ); out.println( "<p>Thank you for participating." ); out.println( "<br />Results:</p><pre>" ); 92 // process results int votes; 95 while ( resultsRS.next() ) { out.print( resultsRS.getString( 1 ) ); out.print( ": " ); votes = resultsRS.getInt( 2 ); out.print( twoDigits.format( ( double ) votes / total * 100 ) ); out.print( "% responses: " ); out.println( votes ); } Create query to get total of all survey responses Execute query to get total of all survey responses SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Line 77 Line 78 Lines Line 85 Create query to get survey results Execute query to get survey results

45 105 resultsRS.close(); 107 out.print( "Total responses: " ); out.print( total ); 110 // end XHTML document out.println( "</pre></body></html>" ); out.close(); 114 } // end try 116 // if database exception occurs, return error page catch ( SQLException sqlException ) { sqlException.printStackTrace(); out.println( "<title>Error</title>" ); out.println( "</head>" ); out.println( "<body><p>Database error occurred. " ); out.println( "Try again later.</p></body></html>" ); out.close(); } 126 } // end of doPost method 128 SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC.

46 Method destroy closes Statement and database connection.
// close SQL statements and database when servlet terminates public void destroy() { // attempt to close statements and database connection try { statement.close(); connection.close(); } 137 // handle database exceptions by returning error to client catch ( SQLException sqlException ) { sqlException.printStackTrace(); } } 143 144 } // end class SurveyServlet Method destroy closes Statement and database connection. SurveyServlet.java Multi-tier Web-based survey using XHTML, servlets and JDBC. Lines

47 <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " 4 <!-- Fig. 24.21: Survey.html --> 6 <html xmlns = " <head> <title>Survey</title> 10 </head> 11 12 <body> 13 <form method = "post" action = "/jhtp5/animalsurvey"> 14 <p>What is your favorite pet?</p> 16 Survey.html document that allows users to submit survey responses to SurveyServlet.

48 <p> <input type = "radio" name = "animal" value = "1" />Dog<br /> <input type = "radio" name = "animal" value = "2" />Cat<br /> <input type = "radio" name = "animal" value = "3" />Bird<br /> <input type = "radio" name = "animal" value = "4" />Snake<br /> <input type = "radio" name = "animal" value = "5" checked = "checked" />None </p> 29 <p><input type = "submit" value = "Submit" /></p> 31 32 </form> 33 </body> 34 </html> Survey.html document that allows users to submit survey responses to SurveyServlet.

49 Survey.html document that allows users to submit survey responses to SurveyServlet.


Download ppt "Servlets Outline Introduction Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle HttpServlet Class HttpServletRequest."

Similar presentations


Ads by Google