Presentation is loading. Please wait.

Presentation is loading. Please wait.

Servlets Included in the J2EE.

Similar presentations


Presentation on theme: "Servlets Included in the J2EE."— Presentation transcript:

1 Servlets Included in the J2EE

2 TOPICS Servlet Basics Setting up the Servlet API
Creating a Web Application The Servlet URL and the Invoking Web Page Servlet Structure Testing a Servlet Passing Data Sessions Cookies Accessing a Database Via a Servlet

3 What isStatic web page accessing
is given in IE x.html

4 Dynamic Web Page Need Suppose at server there is database of items and stock,purchase details and server wants to make it available to the client via webpage Server needs to process something and then generate the content Hence dynamic web page

5 Solutions for dynamic web page
CGI(Common gateway interface) Servlets and JSP ASP And many

6 What is CGI What is the disadv. Of CGI
CommonGatewayInterfaces Small programs requested by client and run on server to generate dynamic content Ex: upon submitting a form you may request a CGI program to be executed and transfer entries entered by client in web page to DB at server.It can be in C++/Perl. But these run as separate processes at Webserver increasing load on web server Hence expensive interms of resources They arenot platform independent DB connection per client request

7 Why are servlets What are the adv?
Improoved Performance They run under the addressspace of web server , hence no separate process environment created per request Platform independent since written in java Webservers from different vendors support servlets It can communicate with applets,databases and other s/w via sockets

8 What are servlets Servlets are java programs which run under the control of web server to help it to generate dynamic web page

9 ServletLifeCycle Three methods are central to the life cycle of any servlet.They are implemented by every servlet and are called at specific times by web server(servlet container ). User enters URL in a Webbrowser Browser genearates an HTTP request and sends to the web server The webserver upon receipt of this request maps this to the particular servlet Then that servlet class is loaded and method init() is called This method is called only once during lifetime of servlet Init is helpful for configuring and setting initial parameters The webserver calls service() next This method actually processes HttpRequest and builds HttpResponse Object For each client request a call to service is made When server decides to shutdown or unload servlet it calls destroy() method The code inside this relinquishes resources such as filehandlers

10 Steps forWriting your own servlet
Installing required s/w ‘s refer other slides named servletinstallinfo.ppt Once everything is set then 1. create and compile the servlet source code 2. start webserver 3.start a web browser and request the servlet

11 A simple HelloServlet import java.io.*; import javax.servlet.*;
public class HelloServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>Hello!"); pw.close(); }

12 The GenericServlet class provides functionality that simplifies the creation of a servlet. For example, it provides versions of init( ) and destroy( ), which may be used as it is. You need supply only the service( ) method. Inside HelloServlet service method is overridden. This method handles request from client

13 Notice that the first argument is a ServletRequest object
Notice that the first argument is a ServletRequest object. This enables the servlet to read data that is provided via the client request. The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client. The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME type is text/html. This indicates that the browser should interpret the content as HTML source code.

14 Next, the getWriter( ) method obtains a PrintWriter
Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response. Then println( ) is used to write some simple HTML source code as the HTTP response.

15 Downloading and configering webserver
From Apache site download Tomcat6.0 binary file and unzip(extract) it to say /home/student. It creates a directory named apachetomcat-versionnumber. Now goto lib subfolder of apachetomcat directory and see if servlet-api.jar is present. Copy this jar file to your student directory

16 Compilation Javac HelloServlet.java -classpath \home\student\servlet-api.jar Above step compiles your servlet code. Now transfer your servlet’s class file to the directory apachetomcat-versionnumber\webapps\examples\WEB-INF\classes In the WEB-INF directory there is an XML file called web.xml

17 Add the following in web.xml file
<servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet-mapping> <url-pattern>/servlet/HelloServlet</url-pattern> </servlet-mapping>

18 Start Tomcat Start Tomcat server by running startup.sh file from bin directory of tomcat6.0. Tomcat must be running before you try to execute a servlet. You can check if tomcat is running by typing in webbrowser and see that it will open homepage of tomcat. Start a Web Browser and Request the Servlet Start a web browser and enter the URL shown here: Alternatively, you may enter the URL shown here:

19 The Servlet API Two packages contain the classes and interfaces that are required to build servlets. javax.servlet javax.servlet.http. They constitute the Servlet API. 4/25/2017 DEPT OF CSE 19

20 The javax.servlet Package
4/25/2017 DEPT OF CSE 20

21 Classes in the servlet package
4/25/2017 DEPT OF CSE 21

22 Methods in servlet package
4/25/2017 DEPT OF CSE 22

23 Servlet Interface All servlet must implement the Servlet interface
It declares the init(), service() and destroy() methods that are called by the server during the life cycle of a servlet- invoked by the server getServletConfig() method is called by the servlet to obtain initialization parameters getServletInfo() is overridden to provide with iuseful information 4/25/2017 DEPT OF CSE 23

24 Methods in Servlet 4/25/2017 DEPT OF CSE 24

25 Servlet Config Interface
This allows a servlet to obtain configuration data when it is loaded 4/25/2017 DEPT OF CSE 25

26 The Servlet Context Interface
Enables servlets to obtain information about their environment 4/25/2017 DEPT OF CSE 26

27 ServletRequest and ServletResponse Interface
Enables a servlet to obtain information about a client request Enables servlet to formulate a response for a client 4/25/2017 DEPT OF CSE 27

28 Methods defined by ServletRequest
4/25/2017 DEPT OF CSE 28

29 Methods defined by ServletResponse
4/25/2017 DEPT OF CSE 29

30 Generic Servlet Class Provides implementations of the basic life cycle methods for a servlet. Implements the Servlet and ServletConfig interfaces Method to append a string to the server log file is available void log(String s) void log(String s, Throwable e) s is the string to be appended to the log, and e is an exception that occurred. 4/25/2017 DEPT OF CSE 30

31 The ServletInputStream Class
The ServletInputStream class extends InputStream. It is implemented by the servlet container and provides an input stream that a servlet developer can use to read the data from a client request. It defines the default constructor. Method is provided to read bytes from the stream. int readLine(byte[ ] buffer, int offset, int size) throws IOException buffer is the array into which size bytes are placed starting at offset. The method returns the actual number of bytes read or –1 if an end-of-stream condition is encountered. 4/25/2017 DEPT OF CSE 31

32 The ServletOutputStream Class
The ServletOutputStream class extends OutputStream. It is implemented by the servlet container and provides an output stream that a servlet developer can use to write data to a client response. A default constructor is defined. It also defines the print( ) and println( ) methods, which output data to the stream. 4/25/2017 DEPT OF CSE 32

33 The Servlet Exception Classes
javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet problem has occurred. Second is UnavailableException, which extends ServletException It indicates that a servlet is unavailable. 4/25/2017 DEPT OF CSE 33

34 Reading Servlet Parameters
The ServletRequest interface includes methods that allow you to read the names and values of parameters that are included in a client request 4/25/2017 DEPT OF CSE 34

35 <html> <body> <center> <form name="Form1“ method="post“ action=" <table> <tr> <td><B>Employee</td> <td><input type=textbox name="e" size="25" value=""></td> </tr> <td><B>Phone</td> <td><input type=textbox name="p" size="25" value=""></td> </table> <input type=submit value="Submit"> </body> </html> 4/25/2017 DEPT OF CSE 35

36 import java. io. ; import java. util. ; import javax. servlet
import java.io.*; import java.util.*; import javax.servlet.*; public class PostParametersServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { // Get print writer. PrintWriter pw = response.getWriter(); // Get enumeration of parameter names. Enumeration e = request.getParameterNames(); // Display parameter names and values. while(e.hasMoreElements()) { String pname = (String)e.nextElement(); pw.print(pname + " = "); String pvalue = request.getParameter(pname); pw.println(pvalue); } pw.close(); } } 4/25/2017 DEPT OF CSE 36

37 The javax.servlet.http Package
4/25/2017 DEPT OF CSE 37

38 Class provided in the javax.servlet.http Package
4/25/2017 DEPT OF CSE 38

39 The HttpServletRequest and HttpServletResponse Interface Interface
The HttpServletRequest interface enables a servlet to obtain information about a client request. The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. Constants that correspond to the different status codes that can be assigned to an HTTP response. SC_OK indicates that the HTTP request succeeded SC_NOT_FOUND indicates that the requested resource is not available. 4/25/2017 DEPT OF CSE 39

40 4/25/2017 DEPT OF CSE 40

41 4/25/2017 DEPT OF CSE 41

42 The HttpSession Interface
The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session. The methods throw an IllegalStateException if the session has already been invalidated. 4/25/2017 DEPT OF CSE 42

43 4/25/2017 DEPT OF CSE 43

44 The HttpSessionBindingListener Interface
The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session. The methods that are invoked when an object is bound or unbound void valueBound(HttpSessionBindingEvent e) void valueUnbound(HttpSessionBindingEvent e) e is the event object that describes the binding. 4/25/2017 DEPT OF CSE 44

45 The Cookie Class The Cookie class encapsulates a cookie.
A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities. The user does not need to enter this data each time he or she visits the store. Aservlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP response that is sent to the browser. 4/25/2017 DEPT OF CSE 45

46 The names and values of cookies are stored on the user’s machine.
The information that is saved for each cookie • The name of the cookie • The value of the cookie • The expiration date of the cookie • The domain and path of the cookie The expiration date determines when this cookie is deleted from the user’s machine. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the user’s machine. 4/25/2017 DEPT OF CSE 46

47 There is one constructor for Cookie. It has the signature shown here:
The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user enters a URL whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise, it is not. There is one constructor for Cookie. It has the signature shown here: Cookie(String name, String value) Name and value of the cookie are supplied as arguments to the constructor 4/25/2017 DEPT OF CSE 47

48 4/25/2017 DEPT OF CSE 48

49 The HttpServlet Class The HttpServlet class extends GenericServlet.
It is commonly used when developing servlets that receive and process HTTP requests. 4/25/2017 DEPT OF CSE 49

50 4/25/2017 DEPT OF CSE 50

51 The HttpSessionEvent Class
HttpSessionEvent encapsulates session events. It extends EventObject and is generated when a change occurs to the session. HttpSessionEvent(HttpSession session) session is the source of the event. HttpSessionEvent defines one method, getSession( ) HttpSession getSession( ) It returns the session in which the event occurred. 4/25/2017 DEPT OF CSE 51

52 4/25/2017 DEPT OF CSE 52

53 The HttpSessionBindingEvent Class
The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is bound to or unbound from a value in an HttpSession object. It is also generated when an attribute is bound or unbound. Here are its constructors: HttpSessionBindingEvent(HttpSession session, String name) HttpSessionBindingEvent(HttpSession session, String name, Object val) Here, session is the source of the event, and name is the name associated with the object that is being bound or unbound. If an attribute is being bound or unbound, its value is passed in val. 4/25/2017 DEPT OF CSE 53

54 The getName( ) method obtains the name that is being bound or unbound.
String getName( ) The getSession( ) method, shown next, obtains the session to which the listener is being bound or unbound: HttpSession getSession( ) The getValue( ) method obtains the value of the attribute that is being bound or unbound. Object getValue( ) 4/25/2017 DEPT OF CSE 54

55 Handling HTTP Requests and Responses
The HttpServlet class provides specialized methods that handle the various types of HTTP requests. doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). 4/25/2017 DEPT OF CSE 55

56 Handling HTTP GET Requests
<html> <body> <center> <form name="Form1" action=" <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html> 4/25/2017 DEPT OF CSE 56

57 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorGetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close(); } } 4/25/2017 DEPT OF CSE 57

58 Handling HTTP POST Requests
<html> <body> <center> <form name="Form1" method="post" action=" <B>Color:</B> <select name="color" size="1"> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <br><br> <input type=submit value="Submit"> </form> </body> </html> 4/25/2017 DEPT OF CSE 58

59 import javax. servlet. ; import javax. servlet. http
import javax.servlet.*; import javax.servlet.http.*; public class ColorPostServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color"); response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>The selected color is: "); pw.println(color); pw.close(); } 4/25/2017 DEPT OF CSE 59

60 Creating a Web Application
A Simple Example

61 Create the following HTML document

62 Servlets must import the following two packages javax.servlet
Servlet Structure Servlets must import the following two packages javax.servlet javax.servlet.http Servlets must extend class HttpServlet from package java.servlet.http. Two most common HTTP requests GET (for multiple data items) POST (for single items)

63 Servlet Structure At the servlet end, method service will despatch either method doGet or method doPost in response to these requests All three methods have a void return type and take the following two arguments: An HttpServletRequest object; An HttpServletResponse object.

64 Servlet Structure HttpServletResponse object has two methods
void setContentType(String <type>) specifies the data type of the response. Normally, this will be "text/HTML". PrintWriter getWriter() Returns the output stream object to which the servlet can write character data to the client.

65 Servlet Structure There are four basic steps in a servlet...
Execute the setContentType method with an argument of "text/HTML". Execute the getWriter method to generate a PrintWriter object. Retrieve any parameter(s) from the initial Web page. Use the println method of the above PrintWriter object to create elements of the Web page to be 'served up' by our Web server.

66 First servlet

67 First servlet

68 Passing Data

69 Passing Data

70 Passing Data The methods of HttpServletRequest that are responsible for handling values/parameters received by servlets are listed below

71 Passing Data

72 Passing Data

73 Passing Data initial page

74 Passing Data servlet-generated

75 Passing Data How to force the browser to reload the original page, rather than retrieve it from its cache, when a return is made to this page.? There is an HTML META tag that will do this, but the tag varies from browser to browser.

76 Passing Data How to force the browser to reload the original page, rather than retrieve it from its cache, when a return is made to this page.? There is an HTML META tag that will do this, but the tag varies from browser to browser. These should be placed immediately after the <HEAD> tag on the initial Web page

77 Passing Data Accepting two numbers, adds them and then displays the result

78 Passing Data Accepting two numbers, adds them and then displays the result

79 Accepting two numbers, adds them and then displays the result
user may enter a non-numeric value, the servlet must cater for a possible NumberFormatException. method getParameter will need to convert the strings it receives into integers by using the parseInt

80

81

82

83

84

85 Sessions

86 Why Sessions? HTTP is that it is a stateless protocol
Each request and each response is a self contained and independent transaction A session is a container where data about a client's activities may be stored and accessed by any of the servlets that have access to the session object.

87 Why Sessions? A session object is created by means of the getSession ()method of HttpServletRequest the server returns the current session if there is one; otherwise, it creates a new session object. For example:

88 Why Sessions? A session object contains a set of name-value pairs.
Each name is of type String and each value is of type Object. Note that objects added to a session must implement the Serializable interface. A servlet may add information to a session object via the following method:

89 Why Sessions? A session object contains a set of name-value pairs.

90 Why Sessions?

91 Why Sessions?

92 Why Sessions?

93 HTML file

94 HTML file

95 HTML file

96 HTML page

97 Selection servlet

98 Selection servlet

99 Selection servlet

100 Selection servlet

101 Selection servlet

102 Selection servlet

103 Selection servlet

104 Initial Page

105 Weight servlet

106 Weight servlet

107 Weight servlet

108 Weight servlet

109 Weight servlet

110 Checkout servlet

111 Checkout servlet

112 Checkout servlet

113 Checkout servlet

114 Checkout servlet

115 Checkout servlet

116 Checkout page

117 What is a Cookie? A cookie is an associated name-value pair in which both name and value are strings. Each cookie is held in a small file sent by the server to the client machine It is retrieved by the server on subsequent visits by the user to the site.

118 What is a Cookie? The constructor for a Java Cookie object must have this signature Once created, it must be added to the HttpServletResponse object via the following HttpServletResponse method :

119 What is a Cookie? Cookies are retrieved via the following method of class HttpServletRequest

120 What is a Cookie? setMaxAge method
Specifies the number of seconds for which the cookie will remain in existence If any negative value is specified, then the cookie goes out of existence when the client browser leaves the site A value of zero causes the cookie's immediate destruction.

121 Example - CookieAdder

122 Example

123 Example

124 Example

125 Example - GetPreferences

126 Example

127 Example

128 Example

129

130 ShowSum Servlet

131 ShowSum Servlet

132 ShowSum Servlet

133 ShowSum Servlet

134 ShowSum Servlet

135 ShowSum Servlet

136 ShowSum Page

137 Accessing a Database Via a Servlet

138 Example

139 Example

140 servlet DbServlet

141 servlet DbServlet

142 servlet DbServlet

143 servlet DbServlet

144 servlet DbServlet

145 servlet DbServlet

146 servlet DbServlet

147 servlet DbServlet

148 servlet DbServlet


Download ppt "Servlets Included in the J2EE."

Similar presentations


Ads by Google