Sie sind auf Seite 1von 17

JAVA &J2EE

10IS753

Unit-6 SERVLETS Before the existence of servlet, there was a concept called CGI (common gateway interface). CGI was creating a separate process for each client request.(this is in terms of processor and memory resources.) For each client request, the database connections to be opened and closed. CGI was not platform independent. These draw back led to the development of concept called "servlet" Servlets execute within the address space of web server. It does not create separate process for each client request. Servlets are platform - independent. Servlets can communicate with applets, databases. Servlets are the programs which run at the server side. For the servlet client is the browser. LIFE CYCLE OF SERVLET: init() service() destroy() These are all methods. init() is used to initialize the life cycle of the servlet. service() is used to receive the request and response the information to the client. destroy() is used to destroy the life cycle of the servlet. init() and destroy() are called internally by the servlet. First, user enters a URL (uniform resource locator) to a web browser. The browser generates a http request for this url and sends it to the
Dept. of ISE, MIT-Mysore Page 1

JAVA &J2EE

10IS753

appropriate server. This http request is received by web server, and then server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server. Then the server invokes the init () method of the servlet. This method is invoked when the servlet is loaded on to the memory. Then server invokes service method, which is called to process the request (http) and generates http response to the client. service(): It contains parameters such as ServletRequest and ServletResponse. NOTE: Servlet remains in the servers address space and is available to process any other http requests received from clients. service() method is called for each client request. destroy(): This method is used to relinquish any resources . Ex: file handles SERVLET API: The two packages required to build servlets. javax.servlet javax.servlet.http javax.servlet: This contains number of classes and interfaces that establish the framework in which Servlets operate.

Dept. of ISE, MIT-Mysore

Page 2

JAVA &J2EE

10IS753

INTERFACE:

Servlet ServletConfig ServletRequest ServletResponse ServletContext

Describes the life cycle of servlet. Allows Servlets to get initialization parameters. Used to read data from the client request. Used to write data to the client response. Enables Servlets to log events and access information about their environment.

SingleThreadModel

Indicates the servlet is threading safe.

CLASS:

GenericServlet ServletInputStream

Implements the servlet and ServletConfig interfaces. Provides an input stream for reading requests from a client.

ServletOutputStream

Provides an output stream for writing responses to a client.

ServletException

Indicates that a servlet error occurred.

Servlet interface: All Servlets must implement the servlet interface. It declares the init() , service() and destroy() methods that are called by the server during life cycle of servlet. void destroy() void init(ServletConfig) void service(ServletRequest rq, ServletResponse rs)

Dept. of ISE, MIT-Mysore

Page 3

JAVA &J2EE

10IS753

GenericServlet CLASS: It provides the implementations of the basic life cycle methods for a servlet. This class implements servlet and ServletConfig interfaces. javax.servlet.http package: This contains several interfaces and classes. The functionalities of this makes easy to build servlets that work with http requests and responses
INTERFACES

HttpServletRequet

Enables the servlet to read data from an http request.

HttpServletResponse Enables the servlet to write data to an http response. HttpSession HttpSessionContext Allows session data to be read and written. Allows sessions to be managed.

CLASS:

Cookie HttpServlet

Allows state information to be stored on a client machine. Provides methods to handle http requests and responses.

The cookie class: The cookie class encapsulates a cookie. A cookie class is stored on a client and contains state information. Cookies are valuable for tracking user activities.

Dept. of ISE, MIT-Mysore

Page 4

JAVA &J2EE

10IS753

Assume that user visits an online store. A cookie can save the users name, address, and other information. The user doesnt need to enter this data each time he or she visits the store. A servlet can write a cookie to a users machine via the addCookie() mathod of the HttpservletResponse interface. The names and values of cookies are stored on the users machine. Some of the information that is saved for each cookie includes the following: The name of the cookie. The value of the cookie. The expiration date of the cookie. The domain and pathof the cookie. The expiration date determines when this cookie is deleted from the users machine. If an expiration date is not explicitly assigned to a cookie, it is deleted, when the current browser ends. Otherwise, the cookie is saved in a file on the users machine. There is one constructor for cookie, it has the following signature. Cookie(String name, String value) The methods of the cookie class are as follows:Method Object clone() String getComment() String getDomain() String getName() String getPath() Description Returns a copy of this object. Returns the comment. Returns the domain. Returns the name. Returns the path.

Dept. of ISE, MIT-Mysore

Page 5

JAVA &J2EE

10IS753

String getValue() void setComment(String c) void setDomain(String d) void setPath(String p)

Returns the value. Sets the comment to c. Sets the domain to d. Sets the path to p.

HttpServlet class:The HttpServlet class extends GenericServlet. It is mainly used when developing servlets that receive and process HTTP requests. The methods of the Httpservlet class are as follows:Method Description

void doDelete(HttpServletRequest rq, Handles the HTTP delete request. HttpServletResponse rs) throws IOException,ServletException void doGet(HttpServletRequest rs) rq, Handles the HTTP Get request.

HttpServletResponse

throws

IOException,ServletException void doPost(HttpServletRequest rs) rq, Handles the HTTP Post request.

HttpServletResponse

throws

IOException,ServletException void doTrace(HttpServletRequest rs) rq, Handles the HTTP Trace request.

HttpServletResponse

throws

IOException,ServletException

Dept. of ISE, MIT-Mysore

Page 6

JAVA &J2EE

10IS753

void

doHead(HttpServletRequest rs)

rq, Handles the HTTP Head request.

HttpServletResponse

throws

IOException,ServletException void doOptions(HttpServletRequest rq, Handles the HTTP options request. HttpServletResponse rs) throws IOException,ServletException void doPut(HttpServletRequest rs) rq, Handles the HTTP Put request.

HttpServletResponse

throws

IOException,ServletException

HANDLING HTTP REQUESTS AND RESPONSE: HttpServlet class provides specialized methods that handle the various types of http requests. They are doGet() doPost() doDelete() doPut() doTrace() These methods to be overridden. Note: GET and POST methods commonly used when handling form input. //prog to select color from the client and send it to the server //server display the color on the client Handling HTTP Post method import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
Dept. of ISE, MIT-Mysore Page 7

JAVA &J2EE

10IS753

public class servlet5a extends HttpServlet { public void doPost(HttpServletRequest rq,HttpServletResponse rs) throws ServletException,IOException { try { String color = rq.getParameter("t1"); rs.setContentType("text/html"); PrintWriter pw = rs.getWriter(); if(color.equals("red")) pw.println("<body bgcolor = red>"); if(color.equals("blue")) pw.println("<body bgcolor = blue>"); if(color.equals("green")) pw.println("<body bgcolor = green>"); pw.println("the selected color is "); pw.println(color); pw.close(); } catch(Exception e) { System.out.print(e); } } }

Dept. of ISE, MIT-Mysore

Page 8

JAVA &J2EE

10IS753

Handling HTTP Get method //prog to select color from the client and send it to the server //server display the color on the client import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class servlet5c extends HttpServlet { public void doGet(HttpServletRequest rq,HttpServletResponse rs) throws ServletException,IOException { try { String color = rq.getParameter("t1"); rs.setContentType("text/html"); PrintWriter pw = rs.getWriter(); if(color.equals("red")) pw.println("<body bgcolor = red>"); if(color.equals("blue")) pw.println("<body bgcolor = blue>"); if(color.equals("green")) pw.println("<body bgcolor = green>"); pw.println("the selected color is "); pw.println(color); pw.close(); } catch(Exception e) { System.out.print(e); } } }
Dept. of ISE, MIT-Mysore Page 9

JAVA &J2EE

10IS753

USING COOKIES: Cookie contains the state information. Cookies are useful for tracking. Storing the information of the client at the client machine itself. Rather than at the server side. //prog accept client information and store in cookies import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class cook1 extends HttpServlet { public void doPost(HttpServletRequest rq,HttpServletResponse rs) throws ServletException,IOException { String data = rq.getParameter("t1"); Cookie c = new Cookie("usercookie",data); rs.addCookie(c); rs.setContentType("text/html"); PrintWriter pw = rs.getWriter(); pw.println("UR INFORMATION HAS BEEN STORED"); pw.println(data); pw.close(); } }

Dept. of ISE, MIT-Mysore

Page 10

JAVA &J2EE

10IS753

<html> <body> <form name="form1" method=post action="http://localhost:8070/abc/storecook"> value<input type=textbox name="t1"> <input type=submit value="go"> </form> </body> </html> The source code for GetCookiesServlet.java is shown in the following listing. It invokes the getCookies() method to read any cookies that are included in the HTTP GET request. The names and values of these cookies are then written to the http response. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetCookiesServlet extends HttpServlet { public void doGet(HttpServletRequest rq,HttpServletResponse rs) throws ServletException,IOException { Cookie c[] = rq.getCookies(); rs.setContentType("text/html"); PrintWriter pw = rs.getWriter(); for(int i=0;i<c.length;i++) { String name=c[i].getName(); String value=c[i].getValue();
Dept. of ISE, MIT-Mysore Page 11

JAVA &J2EE

10IS753

pw.println("name="+name+" "+"value="+value); } pw.close(); } } SESSION TRACKING: A session is created each time a client requests service from a java servlet. The java servlet processes the request and responds accordingly. After which the session is terminated. Many times the same client follows with another request to the same java servlet, and the java servlet requires information regarding the previous session to process the request. HTTP is a stateless protocol. It means that each request is independent of the previous one. There is not any holdover from previous sessions. Using http, sessions cannot be tracked. In some applications, it is necessary to save the state information. So that information can be collected from several interactions between a browser and a server. A java servlet is capable of tracking sessions by using HttpSession API. The HttpSession API uses the HttpSession object that is associated with the HttpServletRequest to determine if the request is a continuation from an existing session or is a new session. A session can be created by using getSession() method of the "HttpServletRequest". An HttpSession" object is returned, this is a new session. This object can store a set of bindings that associate names with objects. The getValue(),
Dept. of ISE, MIT-Mysore

getValueNames(), removeValue()

are methods of
Page 12

HttpSession manage these bindings.

JAVA &J2EE

10IS753

The getSession() method requires one argument , which is a Boolean true. This method returns null, if the user does not have a session. Otherwise new HttpSession object is created. An HttpSession object contains a data structure that is used to store keys and a value associated with each key. a key is an attribute of the session. The value of an attribute can be read by using getAttribute() method of HttpSession. And it can be modified by using setAttribute() method. The getAttribute() required one argument. It is a string object that contains the name of the attribute whose value can be retrieved. The setAttribute() method requires two arguments. The first argument is string object that contains the name of the attribute. The other argument is similar to an object returned by the getAttribute() method. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.net.*; import java.util.*; public class showsession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
//Get the HttpSession Object

Dept. of ISE, MIT-Mysore

Page 13

JAVA &J2EE

10IS753

HttpSession hs=request.getSession(true);
//Get writer

response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.print("<B>");


//Display date and time of last access

Date date=(Date)hs.getAttribute("date"); if(date!=null) { pw.println("last access time is:"+date); }


//Display current date or time.

date=new Date(); hs.setAttribute("date",date); pw.println("current date is:"+date); } } When you first request this servlet, the browser displays one line with the current date and time information. On subsequent invocations, two lines are displayed. The first line shows the date and time when the servlet was last accessed. The second line shows the current date and time.

Dept. of ISE, MIT-Mysore

Page 14

JAVA &J2EE

10IS753

Q. Write a JAVA Servlet which reads two parameters from the web page, say, value1 and value2 which are of type integers, and find sum of the two integers, and return back the result as a web page. Add.html <html> <body> <form name='f1' action='http://localhost:8080/servlets-examples/Add' method='get'> First Number: <input type='text' name='value1'> <br> Second Number: <input type='text' name='value2'> <br> <input type='submit' name='submit' value='submit'> </body> </html> Add.java import java.io.*; public class Add extends Httpservlet { public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException { PrintWriter pw = res.getWriter(); res.setContentType(text/html); int x = Integer.parseInt(req.getParameter("value1")); int y = Integer.parseInt(req.getParameter("value2")); pw.println("The addition of two numbers is "+ (x+y)); } }

Dept. of ISE, MIT-Mysore

Page 15

JAVA &J2EE

10IS753

Q. Write a program using Servlet which contains HTML page with various color options. When user chooses the particular color, the background of that page should be changed accordingly. ColorServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ColorServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException { res.setContentType("Text/Html"); String c=req.getParameter("color"); PrintWriter pw=res.getWriter(); if(c.equals("red")) pw.println("<body BGCOLOR=red>"); if(c.equals("green")) pw.println("<body BGCOLOR=green>"); if(c.equals("green")) pw.println("<body BGCOLOR=green>"); if(c.equals("blue")) pw.println("<body BGCOLOR=blue>"); if(c.equals("yellow")) pw.println("<body BGCOLOR=yellow>"); if(c.equals("black")) pw.println("<body BGCOLOR=black>"); pw.println("<center><h2>The selected color is:"+c+"</h2></center>");; pw.close(); } } ColorServlet.html <HTML> <BODY> <FORM method=get action="http://127.0.0.1:8080/examples/servlets/servlet/ColorServlet">
Dept. of ISE, MIT-Mysore Page 16

JAVA &J2EE

10IS753

Select Color : <select name="color" id="color" size=1> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> <option value="yellow">yellow</option> <option value="black">Black</option> </Select> <input type="submit" value="Submit"> </FORM> </BODY> </HTML>

Dept. of ISE, MIT-Mysore

Page 17

Das könnte Ihnen auch gefallen