0% found this document useful (0 votes)
15 views

Module - 4 Servlet

Servlets java

Uploaded by

sabeeltanveer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Module - 4 Servlet

Servlets java

Uploaded by

sabeeltanveer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Advanced Java & J2EE (18CS644)

MODULE -04
SERVLETS & JSP
SERVLETS
Servlet is a technology which is used to create a java based web application. Servlet is an API that
provides many interfaces and classes including documentation.
Servlet is an interface that must be implemented for creating any Servlet. Servlet is a class that
extends the capabilities of the servers and responds to the incoming requests. It can respond to any
requests.

Advantages of Servlet over CGI

 Servlet is a web component that is deployed on the server to create a dynamic web page.
 Servlets offer several advantages in comparison with CGI.
 First, performance is significantly better. Servlets execute within the address space of a
web server. It is not necessary to create a separate process to handle each client request.
 Second, servlets are platform-independent because they are written in Java.
 Third, the Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine.
 Finally, the full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software.

LIFE CYCLE OF A SERVLET


A servlet life cycle can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet.

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 1


Advanced Java & J2EE (18CS644)

 The servlet is initialized by calling the init() method.


 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.

Init( ) method
 The web container calls the init method only once after creating the Servlet instance.
 The init method is used to initialize the Servlet.
 Syntax of the init method is
public void init(ServletConfig config) throws ServletException

service ( ) method
 The web container calls the service method each time when request for the Servlet is received.
 If Servlet is not initialized, it follows the first three steps then calls the service method.
 If Servlet is initialized, it calls the service method.
 The syntax of the service method of the Servlet interface is given below
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException

destroy( ) method
 The web container calls the destroy method before removing the Servlet instance from the
service.
 It gives the Servlet an opportunity to clean up any resource for example memory, thread etc.

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 2


Advanced Java & J2EE (18CS644)

 The syntax of the destroy method of the Servlet interface is given below:
public void destroy()

USING TOMCAT FOR SERVLET DEVELOPMENT


 To create servlets, you will need access to a servlet development environment.
 The one used by this chapter is Tomcat. Tomcat is an open-source product maintained by the
Jakarta Project of the Apache Software Foundation.
 It contains the class libraries, documentation, and runtime support that you will need to create
and test servlets.
 We can download Tomcat from jakarta.apache.org. The default location for Tomcat 5.5.17 is
C:\Program Files\Apache Software Foundation\Tomcat 5.5\
 If we load Tomcat in a different location, we will need to make appropriate changes to the
examples.
 We may need to set the environmental variable JAVA_HOME to the top-level directory in
which the Java Development Kit is installed.
 To start Tomcat, select Configure Tomcat in the Start Programs menu, and then press Start in the
Tomcat Properties dialog.
 When we are done testing servlets, you can stop Tomcat by pressing Stop in the Tomcat
Properties dialog.
 The directory C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\
contains servlet-api.jar.
 This JAR file contains the classes and interfaces that are needed to build servlets.
 To make this file accessible, update the CLASSPATH environment variable so that it includes
C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\servlet-api.jar
 Alternatively, we can specify this file when we compile the servlets.

For example, the following command compiles the first servlet example
 javac HelloServlet.java -classpath "C:\Program Files\Apache Software Foundation\Tomcat
5.5\common\lib\servlet-api.jar"
 Once we have compiled a servlet, we must enable Tomcat to find it. This means putting it into a
directory under Tomcat’s webapps directory and entering its name into a web.xml file.
Procedure followed is
 First, copy the servlet’s class file into the following directory:
 C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\WEB-
INF\classes
 Next, add the servlet’s name and mapping to the web.xml file in the following directory:

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 3


Advanced Java & J2EE (18CS644)

 C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\WEB-


INF

A SIMPLE SERVLET
The basic steps for creating any servlet program is as follow:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper
directory, and add the servlet’s name and mappings to the proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
Create and Compile the Servlet Source Code
HelloServlet.java
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();
}
}

Web.xml
<web-app>
<Servlet>
<servlet-name>Example</servlet>
<servlet-class>HelloServlet</servlet>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet>
<url-pattren>/Helloservlet</url-pattren>
</servlet-mapping>
</web-app>

 Compile this source code and place the HelloServlet.class file in the proper Tomcat directory.
Add HelloServlet to the web.xml file and then Start Tomcat.
 Start a Web Browser and Request the Servlet Start a web browser and enter the URL shown
here: http://localhost:8080/servlets-examples/servlet/HelloServlet.

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 4


Advanced Java & J2EE (18CS644)

THE SERVLET API


 Two packages contain the classes and interfaces that are required to build servlets. These are
javax.servlet and javax.servlet.http.
 These packages are not part of the Java core packages. Instead, they are standard extensions
provided by Tomcat.
JAVAX.SERVLET PACKAGE
 The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
 The below table summarizes the core interfaces that are provided in this package.

 The most significant of these is Servlet. All servlets must implement this interface or extend a
class that implements the interface.
 The ServletRequest and ServletResponse interfaces are also very important.

The below table summarizes the core classes that are provided in the javax.servlet package:

SERVLET INTERFACE
 All servlets 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.
 The methods defined by Servlet are shown in Table

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 5


Advanced Java & J2EE (18CS644)

 The getServletConfig( ) method is called by the servlet to obtain initialization parameters.


 A servlet developer overrides the getServletInfo( ) method to provide a string with useful
information (for example, author, version, date, copyright). This method is also invoked by the
server.

Example Program
import java.io.*;
import javax.servlet.*;
public class First implements Servlet
{
ServletConfig config=null;

public void init(ServletConfig config)


{
this.config=config;
System.out.println("servlet is initialized");
}
public void service(ServletRequest req,ServletResponse res)throws IOException,
ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}
public void destroy()
{
System.out.println("servlet is destroyed");
}
public ServletConfig getServletConfig()
{
return config;
}
public String getServletInfo()
{

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 6


Advanced Java & J2EE (18CS644)

return "copyright 2007-1010";


}
}

Web.xml
<web-app>
<servlet>
<servlet-name>ServletInterface</servlet-name>
<servlet-class> First </servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ServletInterface</servlet-name>
<url-pattern>/abc </url-pattern>
</servlet-mapping>
</web-app>

SERVLETCONFIG INTERFACE
 An object of ServletConfig is created by the web container for each servlet. This object can be
used to get configuration information from web.xml file.
 The ServletConfig interface allows a servlet to obtain configuration data when it is loaded.
 The methods declared by this interface are

Example
import java.io.*;
import javax.servlet.*;
public class DemoServlet extends GenericServlet
{
public void Service(ServletRequest request, ServletResponse response) throws ServletExce
ption, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
Enumeration < String > e = config.getInitParameterNames();
String str;
while (e.hasMoreElements())
{

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 7


Advanced Java & J2EE (18CS644)

str = e.nextElement();
printWriter.println("<br>Param Name: " + str);
printWriter.println(" value: " + sc.getInitParameter(str));
}
out.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>system</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>

SERVLETCONTEXT INTERFACE
The ServletContext interface enables servlets to obtain information about their environment.
Several of its methods are

web.xml
<web-app>
<servlet>

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 8


Advanced Java & J2EE (18CS644)

<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
Servletrequets.java
import java.io.*;
import javax.servlet.*;
public class DemoServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletExcep
tion, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig();
String str=req.getMimeType(“web.xml”);
out.println(“MIME Type =” +str);
String path=req.getRealPath(“/example/Servletrequest.java”);
out.println(“Real path=” +path);
String info= req.getServerInfo();
out.println(“servlet information=” +info);
out.close();
}
}
SERVLETREQUEST INTERFACE
 The ServletRequest interface is used to handle client request to access a servlet i.e it enables a
servlet to obtain information about a client request.
 It provides the information of a servlet like content type, content length, parameter names and
values etc.
 Several of its methods are

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 9


Advanced Java & J2EE (18CS644)

index.html
<form action="test" method="post">
User Name: <input type="text" name="uname"><br>
Password: <input type = "password name = "password"><br>
<input type="submit" value="Log In">
</form>
web.xml
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>

ServletDemo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 10


Advanced Java & J2EE (18CS644)

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
try
{
String username = req.getParameter("username");
String password = req.getParameter("password");
pw.println("<h1> Hello"+username+"<h1>");
String cp=req.getContentType( );
pw.println(“Content Type=” +cp);
int cl= req.getContentLength( );
pw.println(“Length of the Content is:” + cl);
String protocol = req.getProtocol( );
pw.println(“ Protocol used is:” + protocol);
String rma = req.getRemoteAddr( );
pw.println(“ Remote Address is:” + rma);
String rmh = req.getRemoteHost( );
pw.println(“ Remote Host is:” + rmh);
int sp = req.getServerPort( );
pw.println(“ Server Port is:” + sp);
}
finally
{
pw.close();
}
}
}
SERVLETRESPONSE INTERFACE
 The servlet container is connected to the web server that receives Http Requests from client on a
certain port.
 When client sends a request to web server, the servlet container creates HttpServletRequest and
HttpServletResponse objects and passes them as an argument to the servlet service() method.
 The ServletResponse interface enables a servlet to formulate a response for a client.

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 11


Advanced Java & J2EE (18CS644)

Several of its methods are

import java.io.*;
import javax.servlet.*;
import java.util.*;
public class MyServlet1 extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException
{
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
response.setContentLength(10);
out.println("<h2>using ServletResponse</h2>");
out.println("Response ContentType : " + response.getContentType() + "<br/>");
out.println("Response Character Encoding : " + response.getCharacterEncoding() + "<br/>");
}
}
GENERICSERVLET CLASS
 The GenericServlet class provides implementations of the basic life cycle methods (init, service,
destroy) for a servlet.
 GenericServlet implements the Servlet and ServletConfig interfaces.
 In addition, a method to append a string to the server log file is available. The signatures of this
method are:
void log(String s)
void log(String s, Throwable e)

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 12


Advanced Java & J2EE (18CS644)

 Here, s is the string to be appended to the log, and e is an exception that occurred.

import java.io.*;
import javax.servlet.*;
public class First extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}

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. In addition, a method is provided to read bytes from the
stream.
 It is shown here:
int readLine(byte[ ] buffer, int offset, int size) throws IOException
 Here, 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.
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.
SERVLET EXCEPTION CLASSES
 javax.servlet defines two exceptions.
 The first is ServletException, which indicates that a servlet problem has occurred.

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 13


Advanced Java & J2EE (18CS644)

 The second is UnavailableException, which extends ServletException which indicates that a


servlet is unavailable.
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.
Example
Postparameter.html
<html>
<body>
<center>
<form name="Form1" method="post" action="http://localhost:8080/servlets
examples/servlet/PostParametersServlet">
<B>Employee <input type=textbox name="e" size="25" value="">
<B>Phone <input type=textbox name="p" size="25" value="">
<input type=submit value="Submit">
</body>
</html>

PostParameterServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
Enumeration e = request.getParameterNames();
while(e.hasMoreElements())
{
String pname = e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 14


Advanced Java & J2EE (18CS644)

The getParameterNames( ) method returns an enumeration of the parameter names and the parameter
value is obtained via the getParameter( ) method.

JAVAX.SERVLET.HTTP PACKAGE
The javax.servlet.http package contains a number of interfaces and classes that are commonly used
by servlet developers.
The following table summarizes the core interfaces that are provided in this package

HTTPSERVLETREQUEST INTERFACE
The HttpServletRequest interface enables a servlet to obtain information about a client request.
Several of its methods are

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 15


Advanced Java & J2EE (18CS644)

Example
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class Home extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
String at=request. getAuthType();
Pw.print(“Authentication Type” +at);
String m=request. getMethod();
Pw.print(“Method used” +m);
String virtualpath=request. getPathlnfo();
Pw.print(“Path of the servlet is” +virtualpath);
String realpath= getpathTranslated();
Pw.print(“RealPath of the servlet is” +realpath);
String query=getQueryString ();
Pw.print(“Query String of the servlet is” +query);
String sid=getRequestedSessionld();
Pw.print(“Session id =” +sid);
} }

HTTPSERVLETRESPONSE INTERFACE
 The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.
Several constants are defined. These correspond to the different status codes that can be assigned
to an HTTP response.
 SC_OK indicates that the HTTP request succeeded, and SC_NOT_FOUND indicates that the
requested resource is not available.
 Several methods of this interface are summarized

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 16


Advanced Java & J2EE (18CS644)

Example
c.html
<html>
<body>
<form method = “GET” action=”LC”>
<table>
<tr><td> Name <input type=”text” name=”t1” value=”Enter Name”) </td>
</tr>
<tr><td> Password <input type=”text” name=”t1” value=”Enter password”) </td>
</tr>
</table>
</body>
</html>

Web.xml
<web-app>
<servlet>
<servlet-name>Example</servlet>
<servlet-class>LC</servlet>
</servlet>
<servlet>
<servlet-name>Ex</servlet>
<servlet-class>home</servlet>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet>
<url-pattren>/LC</url-pattren>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Ex</servlet>
<url-pattren>/home</url-pattren>
</servlet-mapping>
</web-app>

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 17


Advanced Java & J2EE (18CS644)

LC.java
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class LC extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
String name=request.getParameter("t1");
String pass=request.getParameter("t2");
if(name.equals(“admin”) && pass.equals(“123”))
{
String URL= response.encodeRedirectURL(“home.java”);
response.sendRedirect(URL);
}
else
{
String URL= response.encodeRedirectURL(“c.html”);
response.sendRedirect(URL);
sendError(100, “Invalid Username”);
}
}
}
Home.java
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class Home extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
Pw.print(“Login Successful”);
}
}

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 18


Advanced Java & J2EE (18CS644)

HTTPSESSION INTERFACE
 The HttpSession interface enables a servlet to read and write the state information that is
associated with an HTTP session.
 Several of its methods are summarized.

 All of these methods throw an IllegalStateException if the session has already been invalidated.

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 are
void valueBound(HttpSessionBindingEvent e)
void valueUnbound(HttpSessionBindingEvent e)
 Here, e is the event object that describes the binding.

HTTPSERVLET CLASSES ARE


The following table summarizes the core classes that are provided in this package. The most
important of these is HttpServlet.

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.

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 19


Advanced Java & J2EE (18CS644)

 A servlet 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.
 The names and values of cookies are stored on the user’s 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 path of the cookie
 There is one constructor for Cookie. It has the signature shown here:
Cookie(String name, String value)
 Here, the name and value of the cookie are supplied as arguments to the constructor.
 The methods of the Cookie class are summarized

Example of Creating, adding cookie, retrieving cookie information


Cookie.html
<html>
<body>

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 20


Advanced Java & J2EE (18CS644)

<center>
<form name="Form1" method="post" action="http://localhost:8080/servlets-
examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String data = request.getParameter("data");
Cookie cookie = new Cookie("MyCookie", data);
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}

GetCookiesServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
{

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 21


Advanced Java & J2EE (18CS644)

String name = cookies[i].getName();


String value = cookies[i].getValue();
pw.println("name = " + name + "; value = " + value);
}
pw.close();
}
}

HTTPSERVLET CLASS
 The HttpServlet class extends GenericServlet. It is commonly used when developing
servlets that receive and process HTTP requests.
 The methods of the HttpServlet class are summarized

Index.html
<html>
<body>
<h1> Student Registration Page</h1>
<form action="/StudentServlet" method="get">
Email ID: <input type="email" name="emailId">
Password: <input type="password" name="password">

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 22


Advanced Java & J2EE (18CS644)

<input type="submit" value="register">


</form>
</body>
</html>

StudentServlet.java
public class StudentServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException
{
String emailId = req.getParameter("emailId");
String password = req.getParameter("password");
resp.setContentType("text/html");
PrintWriter printWriter = resp.getWriter();
printWriter.print(password);
printWriter.print(emailId);
}
}

HTTPSESSIONEVENT CLASS
 HttpSessionEvent encapsulates session events. It extends EventObject and is generated when a
change occurs to the session. It defines this constructor:
HttpSessionEvent(HttpSession session)
 Here, session is the source of the event.
 HttpSessionEvent defines one method, getSession( ), which is shown here:
HttpSession getSession( )
 It returns the session in which the event occurred.

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.
 The getName( ) [ String getName( ) ] method obtains the name that is being bound or unbound.

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 23


Advanced Java & J2EE (18CS644)

 The getSession( ) [ HttpSession getSession( ) ] method obtains the session to which the listener
is being
 The getValue( ) [ Object getValue( ) ]method obtains the value of the attribute that is being
bound or unbound.

HANDLING HTTP REQUESTS AND RESPONSES


Handling HTTP GET Requests
<html>
<body>
<center>
<form name="Form1" action="http://localhost:8080/servlets-examples/servlet/ColorGetServlet">
<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>
ColorGetServlet.java
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();
}
}

Handling HTTP POST Requests


<html>
<body>

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 24


Advanced Java & J2EE (18CS644)

<center>
<form method =”POST” action="http://localhost:8080/servlets-examples/servlet/ColorGetServlet">
<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>

ColorGetServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet 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();
}
}

SESSION TRACKING
 HTTP is a stateless protocol. Each request is independent of the previous one.
 In some applications, it is necessary to save state information so that information can be
collected from several interactions between a browser and a server.
 A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession
object is returned.
 This object can store a set of bindings that associate names with objects. The setAttribute( ),
getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage
these bindings.
Example

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 25


Advanced Java & J2EE (18CS644)

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
HttpSession hs = request.getSession(true);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
Date date = (Date)hs.getAttribute("date");
if(date != null)
{
pw.print("Last access: " + date + "<br>");
}
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}

Prepared by Shilpa, Assistant Professor, Dept. of CSE, NCEH 26

You might also like