Servlets Pearson Education, Inc. All rights reserved.

Size: px
Start display at page:

Download "Servlets Pearson Education, Inc. All rights reserved."

Transcription

1 1 26 Servlets

2 2 A fair request should be followed by the deed in silence. Dante Alighieri The longest part of the journey is said to be the passing of the gate. Marcus Terentius Varro If nominated, I will not accept; if elected, I will not serve. General William T. Sherman Friends share all things. Pythagoras

3 3 OBJECTIVES In this chapter you will learn: How servlets can be used to extend a Web server's functionality. The servlet life cycle. To execute servlets with the Apache Tomcat server. To be able to respond to HTTP requests from an HttpServlet. To be able to redirect requests to static and dynamic Web resources. To use JDBC from a servlet.

4 Introduction 26.2 Servlet Overview and Architecture Interface Servlet and the Servlet Life Cycle HttpServlet Class HttpServletRequest Interface HttpServletResponse Interface 26.3 Setting Up the Apache Tomcat Server 26.4 Handling HTTP get Requests Deploying a Web Application 26.5 Handling HTTP get Requests Containing Data 26.6 Handling HTTP post Requests 26.7 Redirecting Requests to Other Resources 26.8 Multitier Applications: Using JDBC from a Servlet 26.9 Welcome Files Wrap-Up Internet and Web Resources

5 Introduction Java networking capabilities Socket-based and packet-based communications Package java.net Remote Method Invocation (RMI) Package java.rmi Common Object Request Broker Architecture (COBRA) Package org.omg Remote Method Invocation over the Internet Inter-Orb Protocol (RMI-IIOP)

6 Introduction (Cont.) Client-server relationship Servlets and JavaServer Pages (JSP) Request-response model Packages javax.servlet javax.servlet.http javax.servlet.jsp javax.servlet.tagext Common implementation of request-response model Web browsers and Web servers Form the Web components of J2EE

7 Introduction (Cont.) Thin clients Provide presentation Do not process data Require fewer computing resources

8 Introduction (Cont.) Apache Jakarta Project and the Tomcat Server Tomcat Jakarta project Official reference implementation of the JSP and servlet standards

9 Servlet Overview and Architecture Servlet Small portion of the content is static text or markup Do not produce content Perform a task on behalf of the client JavaServer Pages Extension of servlet technology Most of the content is static text or markup Small portion of the content is generated dynamically Servlet container (servlet engine) Server that executes a servlet

10 26.2 Servlet Overview and Architecture (Cont.) 10 Web servers and application servers Sun Java System Application Server Microsoft s Internet Information Server (IIS) Apache HTTP Server BEA s WebLogic Application Server IBM s WebSphere Application Server World Wide Web Consortium s Jigsaw Web Server

11 11 Fig Servlet architecture.

12 Interface Servlet and the Servlet Life Cycle 12 Interface Servlet 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 Servlet s service method handles requests Servlet s destroy method releases servlet resources when the servlet container terminates the servlet Servlet implementation GenericServlet HttpServlet

13 13 Software Engineering Observation 26.1 Servlets implement the Servlet interface of package javax.servlet.

14 14 Method Description void init( ServletConfig config ) The servlet container calls this method once during a servlet s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet. ServletConfig getservletconfig() This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet s configuration information, such as its initialization parameters and ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes). String getservletinfo() This method is defined by a servlet programmer to return a string containing servlet information, such as the servlet s author and version. void service( ServletRequest request, ServletResponse response ) The servlet container calls this method to respond to a client request to the servlet. void destroy() This cleanup method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as open files or open database connections, should be deallocated here. Fig Servlet interface methods.

15 Interface Servlet and the Servlet Life Cycle (Cont.) 15 Interface Servlet implementation GenericServlet Abstract class Package javax.servlet Protocol-independent servlet HttpServlet Abstract class Package javax.servlet.http Use the HTTP protocol to exchange information Key method service ServletRequest and ServletResponse

16 HttpServlet Class Overrides method service Two most common HTTP request types get requests Get/retrieve information from server post requests Post/send data to server Method doget responds to get requests Method dopost responds to post requests HttpServletRequest and HttpServletResponse objects

17 17 Method dodelete dohead dooptions doput dotrace Description Called in response to an HTTP delete request. Such a request is normally used to delete a file from a server. This may not be available on some servers because of its inherent security risks (e.g., the client could delete a file that is critical to the execution of the server or an application). Called in response to an HTTP head request. Such a request is normally used when the client wants only the response s headers, such as its content type and content length. By overriding this method, the servlet does not compute the response body, thus improving performance. Called in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such as the HTTP version (1.0 or 1.1) and the request methods the server supports. Called in response to an HTTP put request. Such a request is normally used to store a file on the server. This may not be available on some servers because of its inherent security risks (e.g., the client could place an executable application on the server, which, if executed, could damage the server perhaps by deleting critical files or occupying resources). Called in response to an HTTP trace request. Such a request is normally used for debugging. The implementation of this method automatically returns an HTML document to the client containing the request header information (data sent by the browser as part of the request). Fig HttpServlet class s other methods.

18 18 Software Engineering Observation 26.2 Do not override method service in an HttpServlet subclass. Doing so prevents the servlet from distinguishing between request types.

19 HttpServletRequest Interface Servlet container creates an HttpServletRequest object passes it to the servlet s service method HttpServletRequest object contains the request from the client provides methods that enable the servlet to process the request

20 20 Method Description String getparameter( String name ) Obtains the value of a parameter sent to the servlet as part of a get or post request. The name argument represents the parameter name. Enumeration getparameternames() Returns the names of all the parameters sent to the servlet as part of a post request. String[] getparametervalues( String name ) For a parameter with multiple values, this method returns an array of strings containing the values for a specified servlet parameter. Cookie[] getcookies() Returns an array of Cookie objects stored on the client by the server. Cookie objects can be used to uniquely identify clients to the servlet. HttpSession getsession( boolean create ) Returns an HttpSession object associated with the client s current browsing session. This method can create an HttpSession object (true argument) if one does not already exist for the client. HttpSession objects and Cookies are used in similar ways for uniquely identifying clients. String getlocalname() Gets the host name on which the request was received. String getlocaladdr() Gets the Internet Protocol (IP) address on which the request was received. int getlocalport() Gets the Internet Protocol (IP) port number on which the request was received. Fig HttpServletRequest methods.

21 HttpServletResponse Interface Servlet container creates an HttpServletResponse object passes it to the servlet s service method HttpServletResponse object provides methods that enable the servlet to formulate the response to the client

22 22 Method Description void addcookie( Cookie cookie ) Used to add a Cookie to the header of the response to the client. The Cookie s maximum age and whether Cookies are enabled on the client determine whether Cookies are stored on the client. ServletOutputStream getoutputstream() Obtains a byte-based output stream for sending binary data to the client. PrintWriter getwriter() Obtains a character-based output stream for sending text data (usually HTML formatted text) to the client. void setcontenttype( String type ) Specifies the content type of the response to the browser. The content type helps the browser determine how to display the data (or possibly what other application to execute to process the data). The content type is also known as MIME (Multipurpose Internet Mail Extension) type of the data. For examples, content type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page; content type "image/gif" indicates that the response is an image, so the browser displays the image. For a complete list of content types, visit String getcontenttype() Gets the content type of the response. Fig HttpServletResponse methods.

23 26.3 Setting Up the Apache Tomcat Server 23 Download Tomcat (version ) apache.towardex.com/jakarta/ tomcat-5/v5.0.25/bin Define environment variables JAVA_HOME C:\Program Files\Java\jdk1.5.0 CATALINA_HOME C:\jakarta-tomcat

24 24 Error-Prevention Tip 26.1 On some platforms you may need to restart your computer for the new environment variables to take effect

25 26.3 Setting Up the Apache Tomcat Server (Cont.) 25 Start the Tomcat server startup Launch the Tomcat server Shutdown the Tomcat server shutdown

26 26 Fig Tomcat documentation home page. Copyright The Apache Software Foundation ( All rights reserved.

27 27 Error-Prevention Tip 26.2 If the host name localhost does not work on your computer, substitute the IP address instead.

28 Handling HTTP get Requests get request Retrieve the content of a URL Example: WelcomeServlet a servlet handles HTTP get requests

29 1 // Fig. 26.7: WelcomeServlet.java 2 // A simple servlet to process get requests. 3 import javax.servlet.servletexception; 4 import javax.servlet.http.httpservlet; 5 import javax.servlet.http.httpservletrequest; 6 import javax.servlet.http.httpservletresponse; 7 import java.io.ioexception; 8 import java.io.printwriter; 9 10 public class WelcomeServlet extends HttpServlet 11 { 12 // process "get" requests from clients 13 protected void doget( HttpServletRequest request, 14 HttpServletResponse response ) 15 throws ServletException, IOException 16 { 17 response.setcontenttype( "text/html" ); 18 PrintWriter out = response.getwriter(); // send XHTML page to client // start XHTML document 23 out.println( "<?xml version = \"1.0\"?>" ); out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC", 26 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"", 27 " \" ); out.println( "<html xmlns = \" ); 30 Outline Import the classes and interfaces in the javax.servlet and javax.servlet.http packages 29 WelcomeServlet.jav a Extends HttpServlet to handle HTTP get requests (1 of 2) and HTTP post requests Override method doget Lines to 3-6 provide custom get request processing Line 10 Uses the response object s setcontenttype Uses the response method object s to specify getwriter the method content to obtain type of a the reference data Lines to to be the sent PrintWriter as the response object to that the enables client the servlet to send content to the client Line 17 Create the XHTML document by writing strings with the out Line 18 object s println method Line Pearson Education, Inc. All rights reserved.

30 31 // head section of document 32 out.println( "<head>" ); 33 out.println( "<title>a Simple Servlet Example</title>" ); 34 out.println( "</head>" ); // body section of document 37 out.println( "<body>" ); 38 out.println( "<h1>welcome to Servlets!</h1>" ); 39 out.println( "</body>" ); // end XHTML document 42 out.println( "</html>" ); 43 out.close(); // close stream to complete the page 44 } // end method doget 45 } // end class WelcomeServlet Outline WelcomeServlet.java (2 of 2) Line 43 Closes the output stream, flushes the output buffer and sends the information to the client Pearson Education, Inc. All rights reserved.

31 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig. 26.7: WelcomeServlet.html --> 6 7 <html xmlns = " 8 <head> 9 <title>handling an HTTP Get Request</title> 10 </head> <body> 13 <form action = "/jhtp6/welcome1" method = "get"> Outline The form s action attribute The form s method attribute (/jhtp6/welcome1) specifies indicates the that the browser sends (1 of a get 2) URL path that invokes the request servlet to the server, which results a call to the servlet s doget method Line <p><label>click the button to invoke the servlet 15 <input type = "submit" value = "Get HTML Document" /> 16 </label></p> 17 </form> 18 </body> 19 </html> 31 WelcomeServlet.htm l Create a button, when clicked, the form s action Line 13is performed Line Pearson Education, Inc. All rights reserved.

32 Outline 32 WelcomeServlet.htm l (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved.

33 33 Software Engineering Observation 26.3 The Tomcat documentation specifies how to integrate Tomcat with popular Web server applications such as the Apache HTTP Server and Microsoft s IIS.

34 34 Common Programming Error 26.1 Using servlet or servlets as a context root may prevent a servlet from working correctly on some servers.

35 Deploying a Web Application Web applications JSPs, servlets and their supporting files Deploying a Web application Directory structure Context root Web application archive file (WAR file) Deployment descriptor web.xml

36 36 Directory context root WEB-INF WEB-INF/classes WEB-INF/lib Description This is the root directory for the Web application. All the JSPs, HTML documents, servlets and supporting files such as images and class files reside in this directory or its subdirectories. The name of this directory is specified by the Web application creator. To provide structure in a Web application, subdirectories can be placed in the context root. For example, if your application uses many images, you might place an images subdirectory in this directory. The examples of this chapter use jhtp6 as the context root. This directory contains the Web application deployment descriptor (web.xml). This directory contains the servlet class files and other supporting class files used in a Web application. If the classes are part of a package, the complete package directory structure would begin here. This directory contains Java archive (JAR) files. The JAR files can contain servlet class files and other supporting class files used in a Web application. Fig Web application standard directories.

37 1 <web-app xmlns=" 2 xmlns:xsi=" 3 xsi:schemalocation=" version="2.4"> 6 7 <!-- General description of your Web application --> 8 <display-name> 9 Java How to Program JSP 10 and Servlet Chapter Examples 11 </display-name> <description> 14 This is the Web application in which we 15 demonstrate our JSP and Servlet examples. 16 </description> <!-- Servlet definitions --> 19 <servlet> 20 <servlet-name>welcome1</servlet-name> <description> 23 A simple servlet that handles an HTTP get request. 24 </description> <servlet-class> 27 WelcomeServlet 28 </servlet-class> 29 </servlet> 30 Outline Web.xml Element display-name Element specifies web-app a defines the configuration name that can be displayed of each to the servlet in the Web application and administrator of the server the on servlet which mapping for each servlet. (1 of 2) the Web application is installed. Element description specifies a Lines 1-37 description of the Web application that might be displayed to the Lines 8-11 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. Element servlet-class specifies compiled servlet s fully qualified class name. Lines Lines Line 20 Lines Lines Pearson Education, Inc. All rights reserved.

38 31 <!-- Servlet mappings --> 32 <servlet-mapping> 33 <servlet-name>welcome1</servlet-name> 34 <url-pattern>/welcome1</url-pattern> 35 </servlet-mapping> </web-app> Element servlet-mapping Outline specifies servlet-name and Element url-pattern helps the server determine url-pattern elements. which requests are sent to the servlet Web.xml (2 of 2) 38 Lines Line Pearson Education, Inc. All rights reserved.

39 Deploying a Web Application (Cont.) 39 Invoke WelcomeServlet example /jhtp6/welcome1 /jhtp6 specifies the context root /welcome1 specifies the URL pattern URL pattern formats Exact match /jhtp5/welcome1 Path mappings /jhtp5/example/* Extension mappings *.jsp Default servlet /

40 40 WelcomeServlet Web application directory and file structure jhtp6 servlets WelcomeServlet.html WEB-INF web.xml classes WelcomeServlet.class Fig Web application directory and file structure for WelcomeServlet.

41 41 Common Programming Error 26.2 Not placing a servlet or other class files in the appropriate directory structure prevents the server from locating those classes properly. This results in an error response to the client Web browser.

42 42 Error-Prevention Tip 26.3 You can test a servlet that handles HTTP get requests by typing the URL that invokes the servlet directly into your browser s Address or Location field because get is the default HTTP method when browsing.

43 26.5 Handling HTTP get Requests Containing Data 43 Servlet WelcomeServlet2 Responds to a get request that contains data

44 1 // Fig : WelcomeServlet2.java 2 // Processing HTTP get requests containing data. 3 import javax.servlet.servletexception; 4 import javax.servlet.http.httpservlet; 5 import javax.servlet.http.httpservletrequest; 6 import javax.servlet.http.httpservletresponse; 7 import java.io.ioexception; 8 import java.io.printwriter; 9 10 public class WelcomeServlet2 extends HttpServlet 11 { 12 // process "get" request from client 13 protected void doget( HttpServletRequest request, 14 HttpServletResponse response ) 15 throws ServletException, IOException 16 { 17 String firstname = request.getparameter( "firstname" ); response.setcontenttype( "text/html" ); 20 PrintWriter out = response.getwriter(); // send XHTML document to client // start XHTML document 25 out.println( "<?xml version = \"1.0\"?>" ); out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC", 28 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"", 29 " \" ); Outline 44 WelcomeServlet2.ja va (1 of 2) Line 17 The request object s getparameter method receives the parameter name and returns the corresponding String value 2005 Pearson Education, Inc. All rights reserved.

45 30 31 out.println( "<html xmlns = \" ); // head section of document 34 out.println( "<head>" ); 35 out.println( 36 "<title>processing get requests with data</title>" ); 37 out.println( "</head>" ); // body section of document 40 out.println( "<body>" ); 41 out.println( "<h1>hello " + firstname + ",<br />" ); 42 out.println( "Welcome to Servlets!</h1>" ); 43 out.println( "</body>" ); // end XHTML document 46 out.println( "</html>" ); 47 out.close(); // close stream to complete the page 48 } // end method doget 49 } // end class WelcomeServlet2 Outline 45 WelcomeServlet2.ja va (2 of 2) Uses the result of line 17 as part of the response Line to the 41 client 2005 Pearson Education, Inc. All rights reserved.

46 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig : WelcomeServlet2.html --> 6 7 <html xmlns = " 8 <head> 9 <title>processing get requests with data</title> 10 </head> <body> 13 <form action = "/jhtp6/welcome2" method = "get"> 14 <p><label> 15 Type your first name and press the Submit button 16 <br /><input type = "text" name = "firstname" /> 17 <input type = "submit" value = "Submit" /> 18 </p></label> 19 </form> 20 </body> 21 </html> Get the first name from the user. Outline 46 WelcomeServlet2.ht ml (1 of 2) Line Pearson Education, Inc. All rights reserved.

47 Outline 47 WelcomeServlet2.ht ml (2 of 2) Program output form data specified in URL s query string as part of a get request 2005 Pearson Education, Inc. All rights reserved.

48 48 Descriptor element Value servlet element servlet-name description servlet-class welcome2 Handling HTTP get requests with data. WelcomeServlet2 servlet-mapping element servlet-name url-pattern welcome2 /welcome2 Fig Deployment descriptor information for servlet WelcomeServlet2.

49 49 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.

50 50 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.

51 51 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.

52 Handling HTTP post Requests HTTP post request Post data from an HTML form to a server-side form handler Browsers cache Web pages Servlet WelcomeServlet3 Responds to a post request that contains data

53 1 // Fig : WelcomeServlet3.java 2 // Processing post requests containing data. 3 import javax.servlet.servletexception; 4 import javax.servlet.http.httpservlet; 5 import javax.servlet.http.httpservletrequest; 6 import javax.servlet.http.httpservletresponse; 7 import java.io.ioexception; 8 import java.io.printwriter; 9 10 public class WelcomeServlet3 extends HttpServlet 11 { 12 // process "post" request from client 13 protected void dopost( HttpServletRequest request, 14 HttpServletResponse response ) 15 throws ServletException, IOException 16 { 17 String firstname = request.getparameter( "firstname" ); response.setcontenttype( "text/html" ); 20 PrintWriter out = response.getwriter(); // send XHTML page to client // start XHTML document 25 out.println( "<?xml version = \"1.0\"?>" ); out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC", 28 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"", 29 " \" ); 30 Outline 53 WelcomeServlet3.ja va (1 of 2) Declare a dopost method to responds to post requests Lines Line 17 The request object s getparameter method receives the parameter name and returns the corresponding String value 2005 Pearson Education, Inc. All rights reserved.

54 31 out.println( "<html xmlns = \" ); // head section of document 34 out.println( "<head>" ); 35 out.println( 36 "<title>processing post requests with data</title>" ); 37 out.println( "</head>" ); // body section of document 40 out.println( "<body>" ); 41 out.println( "<h1>hello " + firstname + ",<br />" ); 42 out.println( "Welcome to Servlets!</h1>" ); 43 out.println( "</body>" ); // end XHTML document 46 out.println( "</html>" ); 47 out.close(); // close stream to complete the page 48 } // end method dopost 49 } // end class WelcomeServlet3 Outline 54 WelcomeServlet3.ja va (2 of 2) 2005 Pearson Education, Inc. All rights reserved.

55 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig : WelcomeServlet3.html --> 6 7 <html xmlns = " 8 <head> 9 <title>handling an HTTP Post Request with Data</title> 10 </head> <body> 13 <form action = "/jhtp6/welcome3" method = "post"> 14 <p><label> 15 Type 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> Outline 55 WelcomeServlet3.ht ml (1 of 2) Provide a form in which Lines the user can input a name in the text input element firstname, then click the Submit button to invoke WelcomeServlet Pearson Education, Inc. All rights reserved.

56 Outline 56 WelcomeServlet3.ht ml (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved.

57 57 Descriptor element Value servlet element servlet-name description servlet-class welcome3 Handling HTTP post requests with data. WelcomeServlet3 servlet-mapping element servlet-name url-pattern welcome3 /welcome3 Fig Deployment descriptor information for servlet WelcomeServlet3.

58 26.7 Redirecting Requests to Other Resources 58 Servlet RedirectServlet Redirects the request to a different resource

59 1 // Fig : RedirectServlet.java 2 // Redirecting a user to a different Web page. 3 import javax.servlet.servletexception; 4 import javax.servlet.http.httpservlet; 5 import javax.servlet.http.httpservletrequest; 6 import javax.servlet.http.httpservletresponse; 7 import java.io.ioexception; 8 import java.io.printwriter; 9 10 public class RedirectServlet extends HttpServlet 11 { 12 // process "get" request from client 13 protected void doget( HttpServletRequest request, 14 HttpServletResponse response ) 15 throws ServletException, IOException 16 { 17 String location = request.getparameter( "page" ); if ( location!= null ) 20 { 21 if ( location.equals( "deitel" ) ) 22 response.sendredirect( " ); 23 else if ( location.equals( "welcome1" ) ) 24 response.sendredirect( "welcome1" ); 25 } // end if // code that executes only if this servlet 28 // does not redirect the user to another page 29 response.setcontenttype( "text/html" ); 30 PrintWriter out = response.getwriter(); Outline 59 RedirectServlet.ja va (1 of 2) Line 17 Lines 21 and 23 Obtains the page parameter from the request. Line 22 Determine if the value is either deitel or welcome1 Redirects the Line request 24 to Redirects the request to the servlet WelcomeServlet Pearson Education, Inc. All rights reserved.

60 31 32 // start XHTML document 33 out.println( "<?xml version = \"1.0\"?>" ); out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC", 36 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"", 37 " \" ); out.println( 40 "<html xmlns = \" ); // head section of document 43 out.println( "<head>" ); 44 out.println( "<title>invalid page</title>" ); 45 out.println( "</head>" ); // body section of document 48 out.println( "<body>" ); 49 out.println( "<h1>invalid page requested</h1>" ); 50 out.println( "<p><a href = " + 51 "\"servlets/redirectservlet.html\">" ); 52 out.println( "Click here to choose again</a></p>" ); 53 out.println( "</body>" ); // end XHTML document 56 out.println( "</html>" ); 57 out.close(); // close stream to complete the page 58 } // end method doget 59 } // end class RedirectServlet Outline 60 RedirectServlet.ja va (2 of 2) 2005 Pearson Education, Inc. All rights reserved.

61 61 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.

62 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig : RedirectServlet.html --> 6 7 <html xmlns = " 8 <head> 9 <title>redirecting a Request to Another Site</title> 10 </head> <body> 13 <p>click a link to be redirected to the appropriate page</p> 14 <p> 15 <a href = "/jhtp6/redirect?page=deitel"> 16 /> 17 <a href = "/jhtp6/redirect?page=welcome1"> 18 Welcome servlet</a> 19 </p> 20 </body> 21 </html> Outline 62 RedirectServlet.ht ml (1 of 2) Lines and Provide links that allow the user to invoke the servlet RedirectServlet 2005 Pearson Education, Inc. All rights reserved.

63 Outline 63 RedirectServlet.ht ml (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved.

64 64 Descriptor element Value servlet element servlet-name description servlet-class servlet-mapping element servlet-name url-pattern redirect Redirecting to static Web pages and other servlets. RedirectServlet redirect /redirect Fig Deployment descriptor information for servlet RedirectServlet.

65 26.8 Multitier Applications: Using JDBC from a Servlet 65 Three-tier distributed applications User interface Business logic Database Web servers often represent the middle tier Three-tier distributed application example SurveyServlet Survey.html MySQL database

66 1 // Fig : SurveyServlet.java 2 // A Web-based survey that uses JDBC from a servlet. 3 package com.deitel.jhtp6.servlets; 4 5 import java.io.printwriter; 6 import java.io.ioexception; 7 import java.sql.connection; 8 import java.sql.drivermanager; 9 import java.sql.statement; 10 import java.sql.resultset; 11 import java.sql.sqlexception; 12 import javax.servlet.servletconfig; 13 import javax.servlet.servletexception; 14 import javax.servlet.unavailableexception; 15 import javax.servlet.http.httpservlet; 16 import javax.servlet.http.httpservletrequest; 17 import javax.servlet.http.httpservletresponse; public class SurveyServlet extends HttpServlet 20 { 21 private Connection connection; 22 private Statement statement; 23 Import interfaces and classes for database manipulation Declare a Connection to manage the Declare database a Statement connection for updating the vote count, totaling all the votes and obtaining the complete survey result Outline 66 SurveyServlet.java (1 of 6) Lines 7-11 Line 21 Line Pearson Education, Inc. All rights reserved.

67 24 // set up database connection and create SQL statement 25 public void init( ServletConfig config ) throws ServletException 26 { 27 // attempt database connection and create Statements 28 try 29 { 30 Class.forName( config.getinitparameter( "databasedriver" ) ); 31 connection = DriverManager.getConnection( 32 config.getinitparameter( "databasename" ) ); 33 config.getinitparameter( "username" ), 34 config.getinitparameter( "password" ) ); // create Statement to query database 37 statement = connection.createstatement(); 38 } // end try 39 // for any exception throw an UnavailableException to 40 // indicate that the servlet is not currently available 41 catch ( Exception exception ) 42 { 43 exception.printstacktrace(); 44 throw new UnavailableException(exception.getMessage()); 45 } // end catch 46 } // end method init 47 Outline Loads the database driver, which is Attempt to open specified (2 a connection of in 6) the to the animalsurvey initialization database, parameter the database databasedriver name, username Line 30 and password are specified in the initialization parameters Create Statement to Lines query database. 67 SurveyServlet.java Line Pearson Education, Inc. All rights reserved.

68 48 // process survey response 49 protected void dopost( HttpServletRequest request, 50 HttpServletResponse response ) 51 throws ServletException, IOException 52 { 53 // set up response to client 54 response.setcontenttype( "text/html" ); 55 PrintWriter out = response.getwriter(); // start XHTML document 58 out.println( "<?xml version = \"1.0\"?>" ); out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC", 61 " \"-//W3C//DTD XHTML 1.0 Strict//EN\"", 62 " \" ); out.println( 65 "<html xmlns = \" ); // head section of document 68 out.println( "<head>" ); // read current survey response 71 int value = 72 Integer.parseInt( request.getparameter( "animal" ) ); 73 String sql; 74 Obtain the survey response Outline 68 SurveyServlet.java (3 of 6) Lines Pearson Education, Inc. All rights reserved.

69 75 // attempt to process a vote and display current results 76 try 77 { 78 // update total for current survey response 79 sql = "UPDATE surveyresults SET votes = votes + 1 " + 80 "WHERE id = " + value; 81 statement.executeupdate( sql ); // get total of all survey responses 84 sql = "SELECT sum( votes ) FROM surveyresults"; 85 ResultSet totalrs = statement.executequery( sql ); 86 totalrs.next(); // position to first record 87 int total = totalrs.getint( 1 ); // get results 90 sql = "SELECT surveyoption, votes, id FROM surveyresults " + 91 "ORDER BY id"; 92 ResultSet resultsrs = statement.executequery( sql ); 93 out.println( "<title>thank you!</title>" ); 94 out.println( "</head>" ); out.println( "<body>" ); 97 out.println( "<p>thank you for participating." ); 98 out.println( "<br />Results:</p><pre>" ); 99 Outline Create sql to update total for current survey response Execute sql statement to update total for current survey response (4 of 6) Create query to get total of all survey Execute responses query to get total of all survey responses Lines SurveyServlet.java Line 81 Create query to get survey Line results 84 Execute query to get survey results Line 85 Lines Line Pearson Education, Inc. All rights reserved.

70 100 // process results 101 int votes; while ( resultsrs.next() ) 104 { 105 out.print( resultsrs.getstring( 1 ) ); 106 out.print( ": " ); 107 votes = resultsrs.getint( 2 ); 108 out.printf( "%.2f", ( double ) votes / total * 100 ); 109 out.print( "% responses: " ); 110 out.println( votes ); 111 } // end while resultsrs.close(); out.print( "Total responses: " ); 116 out.print( total ); // end XHTML document 119 out.println( "</pre></body></html>" ); 120 out.close(); 121 } // end try 122 // if database exception occurs, return error page 123 catch ( SQLException sqlexception ) 124 { 125 sqlexception.printstacktrace(); 126 out.println( "<title>error</title>" ); 127 out.println( "</head>" ); 128 out.println( "<body><p>database error occurred. " ); 129 out.println( "Try again later.</p></body></html>" ); Outline Loop through all records in resultsrs Obtain the value of the first column from the current record Obtain the value of the second column from the current record (5 of 6) 70 SurveyServlet.java Lines Line 105 Line Pearson Education, Inc. All rights reserved.

71 130 out.close(); 131 } // end catch 132 } // end method dopost // close SQL statements and database when servlet terminates 135 public void destroy() 136 { 137 // attempt to close statements and database connection 138 try 139 { 140 statement.close(); 141 connection.close(); 142 } // end try 143 // handle database exceptions by returning error to client 144 catch ( SQLException sqlexception ) 145 { 146 sqlexception.printstacktrace(); 147 } // end catch 148 } // end method destroy 149 } // end class SurveyServlet Close Statement and database connection Outline 71 SurveyServlet.java (6 of 6) Lines Pearson Education, Inc. All rights reserved.

72 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " 4 5 <!-- Fig : Survey.html --> 6 7 <html xmlns = " 8 <head> 9 <title>survey</title> 10 </head> <body> 13 <form method = "post" action = "/jhtp6/animalsurvey"> 14 <p>what is your favorite pet?</p> 15 <p> 16 <input type = "radio" name = "animal" 17 value = "1" />Dog<br /> 18 <input type = "radio" name = "animal" 19 value = "2" />Cat<br /> 20 <input type = "radio" name = "animal" 21 value = "3" />Bird<br /> 22 <input type = "radio" name = "animal" 23 value = "4" />Snake<br /> 24 <input type = "radio" name = "animal" 25 value = "5" checked = "checked" />None 26 </p> 27 <p><input type = "submit" value = "Submit" /></p> 28 </form> 29 </body> 30 </html> Outline Survey.html (1 of 2) Provide a form in which the user can select an animal from a list of radio button, then click the Submit button to invoke animalsurvey Pearson Education, Inc. All rights reserved.

73 Outline 73 Survey.html (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved.

74 74 Descriptor element Value servlet element servlet-name description servlet-class init-param param-name param-value init-param param-name param-value init-param param-name param-value init-param param-name param-value servlet-mapping element servlet-name url-pattern animalsurvey Connecting to a database from a servlet. com.deitel.jhtp6.servlets.surveyservlet databasedriver com.mysql.jdbc.driver databasename jdbc:mysql://localhost/animalsurvey username jhtp6 password jhtp6 animalsurvey /animalsurvey Fig Deployment descriptor information for servlet SurveyServlet.

75 Welcome Files Welcome files Ordered list of files HTML, JSP documents Loaded when the request URL is not mapped to a servlet Defined using the welcome-file-list element Contain one or more welcome-file elements Specify the partial URL of a welcome file Without a leading or trailing / E.g., specify index.html and index.htm as welcome files <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> </welcome-file-list>

76 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" <!-- Fig : index.html --> 6 7 <html xmlns = " 8 <head> 9 <title>welcome File</title> 10 </head> <body> 13 <p>click a link to test each example demonstrated in this chapter</p> 14 <p> 15 <a href = "/jhtp6/servlets/welcomeservlet.html"> 16 WelcomeServlet</a><br /> 17 <a href = "/jhtp6/servlets/welcomeservlet2.html"> 18 WelcomeServlet2</a><br /> 19 <a href = "/jhtp6/servlets/welcomeservlet3.html"> 20 WelcomeServlet3</a><br /> 21 <a href = "/jhtp6/servlets/redirectservlet.html"> 22 RedirectServlet</a><br /> 23 <a href = "/jhtp6/servlets/survey.html"> 24 SurveyServlet</a><br /> 25 </p> 26 </body> 27 </html> Outline index.html (1 of 2) Lines Provide links to test all the examples demonstrated in this chapter Pearson Education, Inc. All rights reserved.

77 Outline 77 index.html (2 of 2) Program output 2005 Pearson Education, Inc. All rights reserved.

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http? What are Servlets? Servlets1 Fatemeh Abbasinejad abbasine@cs.ucdavis.edu A program that runs on a web server acting as middle layer between requests coming from a web browser and databases or applications

More information

Introdução a Servlets

Introdução a Servlets Introdução a Servlets Sumário 7.1.1.Introdução 7.1.2.Servlet Overview and Architecture 7.1.2.1 Interface Servlet and the Servlet Life Cycle 7.1.2.2 HttpServlet Class 7.1.2.3 HttpServletRequest Interface

More information

Servlet Fudamentals. Celsina Bignoli

Servlet Fudamentals. Celsina Bignoli Servlet Fudamentals Celsina Bignoli bignolic@smccd.net What can you build with Servlets? Search Engines E-Commerce Applications Shopping Carts Product Catalogs Intranet Applications Groupware Applications:

More information

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1 Java Enterprise Edition Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1 Java Beans Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 2 Java Bean POJO class : private Attributes public

More information

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON- Ordering Information: Advanced Java 2 Platform How to Program View the complete Table of Contents Read the Preface Download the Code Examples To view all the Deitel products and services available, visit

More information

Session 8. Introduction to Servlets. Semester Project

Session 8. Introduction to Servlets. Semester Project Session 8 Introduction to Servlets 1 Semester Project Reverse engineer a version of the Oracle site You will be validating form fields with Ajax calls to a server You will use multiple formats for the

More information

JAVA SERVLET. Server-side Programming INTRODUCTION

JAVA SERVLET. Server-side Programming INTRODUCTION JAVA SERVLET Server-side Programming INTRODUCTION 1 AGENDA Introduction Java Servlet Web/Application Server Servlet Life Cycle Web Application Life Cycle Servlet API Writing Servlet Program Summary 2 INTRODUCTION

More information

Java Servlets. Preparing your System

Java Servlets. Preparing your System Java Servlets Preparing to develop servlets Writing and running an Hello World servlet Servlet Life Cycle Methods The Servlet API Loading and Testing Servlets Preparing your System Locate the file jakarta-tomcat-3.3a.zip

More information

Advanced Web Technology

Advanced Web Technology Berne University of Applied Sciences Dr. E. Benoist Winter Term 2005-2006 Presentation 1 Presentation of the Course Part Java and the Web Servlet JSP and JSP Deployment The Model View Controler (Java Server

More information

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4 CMPUT 391 Database Management Systems The Basic Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems

More information

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle Introduction Now that the concept of servlet is in place, let s move one step further and understand the basic classes and interfaces that java provides to deal with servlets. Java provides a servlet Application

More information

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2 Java Servlets Adv. Web Technologies 1) Servlets (introduction) Emmanuel Benoist Fall Term 2016-17 Introduction HttpServlets Class HttpServletResponse HttpServletRequest Lifecycle Methods Session Handling

More information

Advanced Internet Technology Lab # 4 Servlets

Advanced Internet Technology Lab # 4 Servlets Faculty of Engineering Computer Engineering Department Islamic University of Gaza 2011 Advanced Internet Technology Lab # 4 Servlets Eng. Doaa Abu Jabal Advanced Internet Technology Lab # 4 Servlets Objective:

More information

ServletConfig Interface

ServletConfig Interface ServletConfig Interface Author : Rajat Categories : Advance Java An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from

More information

Session 9. Introduction to Servlets. Lecture Objectives

Session 9. Introduction to Servlets. Lecture Objectives Session 9 Introduction to Servlets Lecture Objectives Understand the foundations for client/server Web interactions Understand the servlet life cycle 2 10/11/2018 1 Reading & Reference Reading Use the

More information

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests What is the servlet? Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently.

More information

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System 15-415 Database Applications Recitation 6 Project 3: CMUQFlix CMUQ s Movies Recommendation System 1 Project Objective 1. Set up a front-end website with PostgreSQL as the back-end 2. Allow users to login,

More information

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

&' () - #-& -#-!& 2 - % (3 3 !!! + #%!%,)& ! # * +, ! "# # $! " &' ()!"#$$&$'(!!! ($) * + #!,)& - #-& +"- #!(-& #& #$.//0& -#-!& #-$$!& 1+#& 2-2" (3" 3 * * +, - -! #.// HttpServlet $ Servlet 2 $"!4)$5 #& 5 5 6! 0 -.// # 1 7 8 5 9 2 35-4 2 3+ -4 2 36-4 $

More information

Web based Applications, Tomcat and Servlets - Lab 3 -

Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems Web based Applications, - - CMPUT 391 Database Management Systems Department of Computing Science University of Alberta The Basic Web Server CMPUT 391 Database Management

More information

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web Introduction to Java Servlets James Baldo Jr. SWE 432 Design and Implementation of Software for the Web Web Applications A web application uses enabling technologies to 1. make web site contents dynamic

More information

Using Java servlets to generate dynamic WAP content

Using Java servlets to generate dynamic WAP content C H A P T E R 2 4 Using Java servlets to generate dynamic WAP content 24.1 Generating dynamic WAP content 380 24.2 The role of the servlet 381 24.3 Generating output to WAP clients 382 24.4 Invoking a

More information

Servlets by Example. Joe Howse 7 June 2011

Servlets by Example. Joe Howse 7 June 2011 Servlets by Example Joe Howse 7 June 2011 What is a servlet? A servlet is a Java application that receives HTTP requests as input and generates HTTP responses as output. As the name implies, it runs on

More information

Servlet Basics. Agenda

Servlet Basics. Agenda Servlet Basics 1 Agenda The basic structure of servlets A simple servlet that generates plain text A servlet that generates HTML Servlets and packages Some utilities that help build HTML The servlet life

More information

SERVLETS INTERVIEW QUESTIONS

SERVLETS INTERVIEW QUESTIONS SERVLETS INTERVIEW QUESTIONS http://www.tutorialspoint.com/servlets/servlets_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Servlets Interview Questions have been designed especially

More information

UNIT-V. Web Servers: Tomcat Server Installation:

UNIT-V. Web Servers: Tomcat Server Installation: UNIT-V Web Servers: The Web server is meant for keeping Websites. It Stores and transmits web documents (files). It uses the HTTP protocol to connect to other computers and distribute information. Example:

More information

Servlets Basic Operations

Servlets Basic Operations Servlets Basic Operations Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh spring@imap.pitt.edu http://www.sis.pitt.edu/~spring Overview Preparing to

More information

Module 4: SERVLET and JSP

Module 4: SERVLET and JSP 1.What Is a Servlet? Module 4: SERVLET and JSP A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper

More information

Servlets. An extension of a web server runs inside a servlet container

Servlets. An extension of a web server runs inside a servlet container Servlets What is a servlet? An extension of a web server runs inside a servlet container A Java class derived from the HttpServlet class A controller in webapplications captures requests can forward requests

More information

Servlets and JSP (Java Server Pages)

Servlets and JSP (Java Server Pages) Servlets and JSP (Java Server Pages) XML HTTP CGI Web usability Last Week Nan Niu (nn@cs.toronto.edu) CSC309 -- Fall 2008 2 Servlets Generic Java2EE API for invoking and connecting to mini-servers (lightweight,

More information

CIS 455 / 555: Internet and Web Systems

CIS 455 / 555: Internet and Web Systems 1 Background CIS 455 / 555: Internet and Web Systems Spring, 2010 Assignment 1: Web and Application Servers Milestone 1 due February 3, 2010 Milestone 2 due February 15, 2010 We are all familiar with how

More information

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY UNIT IV SERVLETS 1. What is Servlets? a. Servlets are server side components that provide a powerful mechanism

More information

Chapter 29 Servlets: Bonus for Java Developers 1041

Chapter 29 Servlets: Bonus for Java Developers 1041 Chapter 29 Servlets: Bonus for Java Developers 1041 29 Servlets: Bonus for Java Developers Method Description void init( ServletConfig config ) This method is automatically called once during a servlet

More information

Unit 5 JSP (Java Server Pages)

Unit 5 JSP (Java Server Pages) Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. It focuses more on presentation logic

More information

9.3.5 Accessing the Vote Service

9.3.5 Accessing the Vote Service jws1_09_article.fm Page 228 Friday, August 9, 2002 11:45 AM Chapter 9 Java API for XML-Based Remote Procedure Calls (JAX-RPC) 228 9.3.5 Accessing the Vote Service Once a Web service is deployed, a client

More information

The Structure and Components of

The Structure and Components of Web Applications The Structure and Components of a JEE Web Application Sample Content garth@ggilmour.com The Structure t of a Web Application The application is deployed in a Web Archive A structured jar

More information

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets ID2212 Network Programming with Java Lecture 10 Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets Leif Lindbäck, Vladimir Vlassov KTH/ICT/SCS HT 2015

More information

Questions and Answers

Questions and Answers Q.1) Servlet mapping defines A. An association between a URL pattern and a servlet B. An association between a URL pattern and a request page C. An association between a URL pattern and a response page

More information

Chapter 10 Servlets and Java Server Pages

Chapter 10 Servlets and Java Server Pages Chapter 10 Servlets and Java Server Pages 10.1 Overview of Servlets A servlet is a Java class designed to be run in the context of a special servlet container An instance of the servlet class is instantiated

More information

SSC - Web applications and development Introduction and Java Servlet (I)

SSC - Web applications and development Introduction and Java Servlet (I) SSC - Web applications and development Introduction and Java Servlet (I) Shan He School for Computational Science University of Birmingham Module 06-19321: SSC Outline Outline of Topics What will we learn

More information

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps. About the Tutorial Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs. Servlets have access to the entire

More information

Trabalhando com JavaServer Pages (JSP)

Trabalhando com JavaServer Pages (JSP) Trabalhando com JavaServer Pages (JSP) Sumário 7.2.1 Introdução 7.2.2 JavaServer Pages Overview 7.2.3 First JavaServer Page Example 7.2.4 Implicit Objects 7.2.5 Scripting 7.2.5.1 Scripting Components 7.2.5.2

More information

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

Advance Java. Configuring and Getting Servlet Init Parameters per servlet Advance Java Understanding Servlets What are Servlet Components? Web Application Architecture Two tier, three tier and N-tier Arch. Client and Server side Components and their relation Introduction to

More information

Université Antonine - Baabda

Université Antonine - Baabda Université Antonine - Baabda Faculté d ingénieurs en Informatique, Multimédia, Systèmes, Réseaux et Télécommunications Applications mobiles (Pocket PC, etc ) Project: Manipulate School Database Préparé

More information

JSP. Common patterns

JSP. Common patterns JSP Common patterns Common JSP patterns Page-centric (client-server) CLIENT JSP or Servlet CLIENT Enterprise JavaBeans SERVER DB Common JSP patterns Page-centric 1 (client-server) Page View request response

More information

Introduction to Servlets. After which you will doget it

Introduction to Servlets. After which you will doget it Introduction to Servlets After which you will doget it Servlet technology A Java servlet is a Java program that extends the capabilities of a server. Although servlets can respond to any types of requests,

More information

COMP9321 Web Application Engineering

COMP9321 Web Application Engineering COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2411 1 Review:

More information

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web UNIT - 4 Servlet 4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web browser and request the servlet, example

More information

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return:

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return: Advanced Java Programming Servlets Chris Wong chw@it.uts.edu.au Orginal notes by Dr Wayne Brookes and Threading Copyright UTS 2008 Servlets Servlets-1 Copyright UTS 2008 Servlets Servlets-2 Quick HTTP

More information

Supplement IV.E: Tutorial for Tomcat For Introduction to Java Programming By Y. Daniel Liang

Supplement IV.E: Tutorial for Tomcat For Introduction to Java Programming By Y. Daniel Liang Supplement IV.E: Tutorial for Tomcat 5.5.9 For Introduction to Java Programming By Y. Daniel Liang This supplement covers the following topics: Obtaining and Installing Tomcat Starting and Stopping Tomcat

More information

11.1 Introduction to Servlets

11.1 Introduction to Servlets 11.1 Introduction to Servlets - A servlet is a Java object that responds to HTTP requests and is executed on a Web server - Servlets are managed by the servlet container, or servlet engine - Servlets are

More information

COMP9321 Web Application Engineering

COMP9321 Web Application Engineering COMP9321 Web Application Engineering Java Server Pages (JSP) Dr. Basem Suleiman Service Oriented Computing Group, CSE, UNSW Australia Semester 1, 2016, Week 3 http://webapps.cse.unsw.edu.au/webcms2/course/index.php?cid=2442

More information

HTTP and the Dynamic Web

HTTP and the Dynamic Web HTTP and the Dynamic Web How does the Web work? The canonical example in your Web browser Click here here is a Uniform Resource Locator (URL) http://www-cse.ucsd.edu It names the location of an object

More information

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature INTRODUCTION TO SERVLETS AND WEB CONTAINERS Actions in Accord with All the Laws of Nature Web server vs web container Most commercial web applications use Apache proven architecture and free license. Tomcat

More information

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR Installing a Web Server 1. Install a sample web server, which supports Servlets/JSPs. A light weight web server is Apache Tomcat server. You can get the server from http://tomcat.apache.org/ 2. Follow

More information

Unit 4 - Servlet. Servlet. Advantage of Servlet

Unit 4 - Servlet. Servlet. Advantage of Servlet Servlet Servlet technology is used to create web application, resides at server side and generates dynamic web page. Before Servlet, CGI (Common Gateway Interface) was popular as a server-side programming

More information

Introduction. This course Software Architecture with Java will discuss the following topics:

Introduction. This course Software Architecture with Java will discuss the following topics: Introduction This course Software Architecture with Java will discuss the following topics: Java servlets Java Server Pages (JSP s) Java Beans JDBC, connections to RDBMS and SQL XML and XML translations

More information

Kamnoetvidya Science Academy. Object Oriented Programming using Java. Ferdin Joe John Joseph. Java Session

Kamnoetvidya Science Academy. Object Oriented Programming using Java. Ferdin Joe John Joseph. Java Session Kamnoetvidya Science Academy Object Oriented Programming using Java Ferdin Joe John Joseph Java Session Create the files as required in the below code and try using sessions in java servlets web.xml

More information

Table of Contents. Introduction... xxi

Table of Contents. Introduction... xxi Introduction... xxi Chapter 1: Getting Started with Web Applications in Java... 1 Introduction to Web Applications... 2 Benefits of Web Applications... 5 Technologies used in Web Applications... 5 Describing

More information

Servlet. 1.1 Web. 1.2 Servlet. HTML CGI Common Gateway Interface Web CGI CGI. Java Applet JavaScript Web. Java CGI Servlet. Java. Apache Tomcat Jetty

Servlet. 1.1 Web. 1.2 Servlet. HTML CGI Common Gateway Interface Web CGI CGI. Java Applet JavaScript Web. Java CGI Servlet. Java. Apache Tomcat Jetty 1 Servlet 1.1 Web Web WWW HTML CGI Common Gateway Interface Web HTML Web Web CGI CGI CGI Perl, PHP C Java Applet JavaScript Web CGI HTML 1.2 Servlet Java Servlet Servlet CGI Web CGI 1 Java Java JVM Java

More information

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22. Answers 1. What is the super interface to all the JDBC Drivers, specify their fully qualified name? a. Java.sql.Driver i. JDBC-ODBC Driver ii. Java-Native API Driver iii. All Java Net Driver iv. Java Native

More information

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003 Introduction This course Software Architecture with Java will discuss the following topics: Java servlets Java Server Pages (JSP s) Java Beans JDBC, connections to RDBMS and SQL XML and XML translations

More information

Servlet and JSP Review

Servlet and JSP Review 2006 Marty Hall Servlet and JSP Review A Recap of the Basics 2 JSP, Servlet, Struts, JSF, AJAX, & Java 5 Training: http://courses.coreservlets.com J2EE Books from Sun Press: http://www.coreservlets.com

More information

Trabalhando com JavaServer Pages (JSP)

Trabalhando com JavaServer Pages (JSP) Trabalhando com JavaServer Pages (JSP) Sumário 7.2.1 Introdução 7.2.2 JavaServer Pages Overview 7.2.3 First JavaServer Page Example 7.2. Implicit Objects 7.2.5 Scripting 7.2.5.1 Scripting Components 7.2.5.2

More information

The Servlet Life Cycle

The Servlet Life Cycle The Servlet Life Cycle What is a servlet? Servlet is a server side component which receives a request from a client, processes the request and sends a content based response back to the client. The Servlet

More information

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA Setting up Java Development Kit This step involves downloading an implementation of the Java Software Development

More information

How does the Web work? HTTP and the Dynamic Web. Naming and URLs. In Action. HTTP in a Nutshell. Protocols. The canonical example in your Web browser

How does the Web work? HTTP and the Dynamic Web. Naming and URLs. In Action. HTTP in a Nutshell. Protocols. The canonical example in your Web browser How does the Web work? The canonical example in your Web browser and the Dynamic Web Click here here is a Uniform Resource Locator (URL) http://www-cse.ucsd.edu It names the location of an object on a

More information

LearningPatterns, Inc. Courseware Student Guide

LearningPatterns, Inc. Courseware Student Guide Fast Track to Servlets and JSP Developer's Workshop LearningPatterns, Inc. Courseware Student Guide This material is copyrighted by LearningPatterns Inc. This content shall not be reproduced, edited, or

More information

Unit-4: Servlet Sessions:

Unit-4: Servlet Sessions: 4.1 What Is Session Tracking? Unit-4: Servlet Sessions: Session tracking is the capability of a server to maintain the current state of a single client s sequential requests. Session simply means a particular

More information

First Servlets. Chapter. Topics in This Chapter

First Servlets. Chapter. Topics in This Chapter First Servlets Chapter Topics in This Chapter The basic structure of servlets A simple servlet that generates plain text The process of compiling, installing, and invoking servlets A servlet that generates

More information

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype=text/html; charset=windows-31j import=java.util.calendar %> A JSP A.1 JSP Servlet Java HTML JSP HTML Java ( HTML JSP ) JSP Servlet Servlet HTML JSP MyDate.jsp

More information

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming PSD1B Advance Java Programming Unit : I-V PSD1B- Advance Java Programming 1 UNIT I - SYLLABUS Servlets Client Vs Server Types of Servlets Life Cycle of Servlets Architecture Session Tracking Cookies JDBC

More information

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil

Servlet And JSP. Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar. Mr. Nilesh Vishwasrao Patil Servlet And JSP, Government Polytechnic, Ahmednagar Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To write servlet for cookies and session

More information

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

This course is intended for Java programmers who wish to write programs using many of the advanced Java features. COURSE DESCRIPTION: Advanced Java is a comprehensive study of many advanced Java topics. These include assertions, collection classes, searching and sorting, regular expressions, logging, bit manipulation,

More information

AJP. CHAPTER 5: SERVLET -20 marks

AJP. CHAPTER 5: SERVLET -20 marks 1) Draw and explain the life cycle of servlet. (Explanation 3 Marks, Diagram -1 Marks) AJP CHAPTER 5: SERVLET -20 marks Ans : Three methods are central to the life cycle of a servlet. These are init( ),

More information

Demonstration of Servlet, JSP with Tomcat, JavaDB in NetBeans

Demonstration of Servlet, JSP with Tomcat, JavaDB in NetBeans Demonstration of Servlet, JSP with Tomcat, JavaDB in NetBeans Installation pre-requisites: NetBeans 7.01 or above is installed; Tomcat 7.0.14.0 or above is installed properly with NetBeans; (see step 7

More information

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers Session 9 Deployment Descriptor Http 1 Reading Reading and Reference en.wikipedia.org/wiki/http Reference http headers en.wikipedia.org/wiki/list_of_http_headers http status codes en.wikipedia.org/wiki/http_status_codes

More information

Fast Track to Java EE 5 with Servlets, JSP & JDBC

Fast Track to Java EE 5 with Servlets, JSP & JDBC Duration: 5 days Description Java Enterprise Edition (Java EE 5) is a powerful platform for building web applications. The Java EE platform offers all the advantages of developing in Java plus a comprehensive

More information

One application has servlet context(s).

One application has servlet context(s). FINALTERM EXAMINATION Spring 2010 CS506- Web Design and Development DSN stands for. Domain System Name Data Source Name Database System Name Database Simple Name One application has servlet context(s).

More information

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013 Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013 Overview Dynamic web content genera2on (thus far) CGI Web server modules Server- side scrip2ng e.g. PHP, ASP, JSP Custom web server Java

More information

SERVLET AND JSP FILTERS

SERVLET AND JSP FILTERS SERVLET AND JSP FILTERS FILTERS OVERVIEW Filter basics Accessing the servlet context Using initialization parameters Blocking responses Modifying responses FILTERS: OVERVIEW Associated with any number

More information

JavaServer Pages (JSP)

JavaServer Pages (JSP) JavaServer Pages (JSP) The Context The Presentation Layer of a Web App the graphical (web) user interface frequent design changes usually, dynamically generated HTML pages Should we use servlets? No difficult

More information

CIS 3952 [Part 2] Java Servlets and JSP tutorial

CIS 3952 [Part 2] Java Servlets and JSP tutorial Java Servlets Example 1 (Plain Servlet) SERVLET CODE import java.io.ioexception; import java.io.printwriter; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet;

More information

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes Session 8 Deployment Descriptor 1 Reading Reading and Reference en.wikipedia.org/wiki/http Reference http headers en.wikipedia.org/wiki/list_of_http_headers http status codes en.wikipedia.org/wiki/_status_codes

More information

CS506 Web Design & Development Final Term Solved MCQs with Reference

CS506 Web Design & Development Final Term Solved MCQs with Reference with Reference I am student in MCS (Virtual University of Pakistan). All the MCQs are solved by me. I followed the Moaaz pattern in Writing and Layout this document. Because many students are familiar

More information

Programming on the Web(CSC309F) Tutorial 9: JavaServlets && JDBC TA:Wael Abouelsaadat

Programming on the Web(CSC309F) Tutorial 9: JavaServlets && JDBC TA:Wael Abouelsaadat Programming on the Web(CSC309F) Tutorial 9: JavaServlets && JDBC TA:Wael Abouelsaadat WebSite: http://www.cs.toronto.edu/~wael Office-Hour: Friday 12:00-1:00 (SF2110) Email: wael@cs.toronto.edu 1 Using

More information

Java Servlets Basic Concepts and Programming

Java Servlets Basic Concepts and Programming Basic Concepts and Programming Giuseppe Della Penna Università degli Studi di L Aquila dellapenna@univaq.it http://www.di.univaq.it/gdellape This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike

More information

Accessing EJB in Web applications

Accessing EJB in Web applications Accessing EJB in Web applications 1. 2. 3. 4. Developing Web applications Accessing JDBC in Web applications To run this tutorial, as a minimum you will be required to have installed the following prerequisite

More information

Getting started with Winstone. Minimal servlet container

Getting started with Winstone. Minimal servlet container Getting started with Winstone Minimal servlet container What is Winstone? Winstone is a small servlet container, consisting of a single JAR file. You can run Winstone on your computer using Java, and get

More information

CREATE A SERVLET PROGRAM TO DISPLAY THE STUDENTS MARKS. To create a servlet program to display the students marks

CREATE A SERVLET PROGRAM TO DISPLAY THE STUDENTS MARKS. To create a servlet program to display the students marks CREATE A SERVLET PROGRAM TO DISPLAY THE STUDENTS MARKS DATE: 30.9.11 Aim: To create a servlet program to display the students marks Hardware requirements: Intel Core 2 Quad 2GB RAM Software requirements:

More information

Table of Contents Fast Track to JSF 2

Table of Contents Fast Track to JSF 2 Table of Contents Fast Track to JSF 2 Fast Track to JavaServer Faces (JSF 2) 1 Workshop Overview / Student Prerequisites 2 Workshop Agenda 3 Typographic Conventions 4 Labs 5 Release Level 6 Session 1:

More information

web.xml Deployment Descriptor Elements

web.xml Deployment Descriptor Elements APPENDIX A web.xml Deployment Descriptor s The following sections describe the deployment descriptor elements defined in the web.xml schema under the root element . With Java EE annotations, the

More information

Advanced Java Programming

Advanced Java Programming Advanced Java Programming Length: 4 days Description: This course presents several advanced topics of the Java programming language, including Servlets, Object Serialization and Enterprise JavaBeans. In

More information

SDN Community Contribution

SDN Community Contribution SDN Community Contribution (This is not an official SAP document.) Disclaimer & Liability Notice This document may discuss sample coding or other information that does not include SAP official interfaces

More information

********************************************************************

******************************************************************** ******************************************************************** www.techfaq360.com SCWCD Mock Questions : Servlet ******************************************************************** Question No :1

More information

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC) Session 8 JavaBeans 1 Reading Reading & Reference Head First Chapter 3 (MVC) Reference JavaBeans Tutorialdocs.oracle.com/javase/tutorial/javabeans/ 2 2/27/2013 1 Lecture Objectives Understand how the Model/View/Controller

More information

SECTION II: JAVA SERVLETS

SECTION II: JAVA SERVLETS Chapter 7 SECTION II: JAVA SERVLETS Working With Servlets Working with Servlets is an important step in the process of application development and delivery through the Internet. A Servlet as explained

More information

Complimentary material for the book Software Engineering in the Agile World

Complimentary material for the book Software Engineering in the Agile World Complimentary material for the book Software Engineering in the Agile World (ISBN: 978-93-5300-898-7) published by Amazon, USA (ISBN: 978-1976901751) and Flushing Meadows Publishers, India (ISBN: 978-93-5300-898-7)

More information

Introduction to JSP and Servlets Training 5-days

Introduction to JSP and Servlets Training 5-days QWERTYUIOP{ Introduction to JSP and Servlets Training 5-days Introduction to JSP and Servlets training course develops skills in JavaServer Pages, or JSP, which is the standard means of authoring dynamic

More information

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p. Preface p. xiii Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p. 11 Creating the Deployment Descriptor p. 14 Deploying Servlets

More information

A Servlet-Based Search Engine. Introduction

A Servlet-Based Search Engine. Introduction A Servlet-Based Search Engine Introduction Architecture Implementation Summary Introduction Pros Suitable to be deployed as a search engine for a static web site Very efficient in dealing with client requests

More information