Servlet Notes
Servlet Notes
Servlet Notes
Request
Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet
{
public void doPost(HttpServletRequest req ,HttpServletResponse
res)throws ServletException,IOException{
res.setContentType(“text/html”)
PrintWriter out=res.getWriter();
out.println("<html>“);
out.println("<head><title>Java
Servlet</title></head>"); out.println("<body>“);
out.println(“<p> My First Servlet program </p>
“); out.println("</body></html>");
}}
A java Servlet is a java class that reads request sent from a client and responds by sending
information to the client.
The java class must extend HttpServlet and override the Httpservlet’s doGet() or doPost()
methods
doGet() used when request is sent using the METHOD=“GET” attribute of HTML
doPost() used when request is sent using the METHOD=“POST” attribute of HTML
Both doGet() and doPost() requires two arguments
The first argument is an HttpservletRequest object
The secons argument is an HttpservletResponse object
The HttpSevletRequest used to receive request from cleint.
The HttpServletResponse is used to Respond to Client.
(format of data response depends on client, ex: data given is in the form of a HTML or XML
page if the client is a browser)
Both throws ServletExcetion and IOException
3.4 Servlet Lifecycle
• The Servlet lifecycle is simple, there is only one main state – “Initialized”.
constructor()
destroy()
init()
Initialized
init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a
servlet.
They are implemented by every servlet and are invoked at specific times by the server.
Procedure:
First, user enters URL, browser then generates an HTTP request for this URL, & this request is
then sent to the appropriate server.
Second, this HTTP request is received by web server, web server maps this request to a particular
servlet.
The servlet is dynamically retrieved & loaded into the address space of the server.
Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet
is first loaded into memory.
It is possible to pass initialization parameters to the servlet so it may configure itself.
Fourth, the server invokes the service ( ) method of the servlet. This method is called to process
the HTTP request. It may also formulate an HTTP response for the client.
The service( ) method is called for each HTTP request.
Finally, the server may decide to unload the servlet from its memory. The server calls the
destroy( ) method to relinquish any resources such as file handles that are allocated for the
servlet.
The Servlet API
Packages
The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
Interface Summary
RequestDispatcher Defines an object that receives requests from the client and sends them
to any resource (such as a servlet, HTML file, or JSP file) on the server.
Servlet Defines methods that all servlets must implement.
ServletConfig A servlet configuration object used by a servlet container to pass
information to a servlet during initialization.
Defines a set of methods that a servlet uses to communicate with its servlet
ServletContext container, for example, to get the MIME type of a file, dispatch requests, or
write to a log file.
ServletRequest
Defines an object to provide client request information to a servlet.
ServletResponse Defines an object to assist a servlet in sending a response to the client
The Servlet Interface Methods:
Method Summary
void destroy()
Called by the servlet container to indicate to a servlet that the servlet is being
taken out of service.
ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup
parameters for this servlet.
java.lang.String getServletInfo()
Returns information about the servlet, such as author, version, and copyright.
void init( ServletConfig config)
Called by the servlet container to indicate to a servlet that the servlet is being
placed into service.
void service( ServletRequest req, ServletResponse res)
Called by the servlet container to allow the servlet to respond to a request.
The following table summarizes the core classes that are provided in the javax.servlet
package.
Class Summary
GenericServlet Defines a generic, protocol-independent servlet.
Provides an input stream for reading binary data from a client
ServletInputStream request, including an efficient readLine method for reading data
one line at a time.
ServletOutputStream Provides an output stream for sending binary data to the client.
This is the event class for notifications of changes to the attributes
ServletRequestAttributeEvent of the servlet request in an application.
ServletRequestEvent Events of this kind indicate lifecycle events for a ServletRequest.
The GenericServlet class provides implementations of the basic life cycle methods 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 shown
here: void log(String s)
void log(String s, Throwable e)
Here, s is the string to be appended to the log, and e is an exception that occurred.
The Servlet Exception Classes
javax.servlet defines two exceptions.
The first is ServletException, which indicates that a servlet problem has occurred.
The second is UnavailableException, which extends ServletException. It indicates that a
servlet is unavailable.
The ServletRequest class includes methods that allow you to read the names and values of
parameters that are included in a client request.
The example contains two files. A Web page is defined in PostParameters.htm and a servlet is
defined in PostParametersServlet.java.
package
ServletPrograms; import
java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
<html>
<body>
<form action="prog2"
method="post"> <table>
<tr>
<td><B>username</b></td>
<td><input type=text
name="username"></td> </tr>
<tr><td><B>password</b></td>
<td><input type=password
name="password"></td> </tr>
</table>
<input type=submit value="submit">
</form>
</body>
</html>
Deployment Descriptor
• How does the Container know which Servlet the client has requested for?
Actual file name
The javax.servlet.http package contains a number of interfaces classes that are commonly used by
servlet developers.
Interface Summary
HttpServlet
The default service() method in an HTTP servlet routes the request to another method based
on the HTTP transfer method (POST, and GET).
HTTP POST requests from HTML file are routed to the doPost() method, HTTP GET
requests are routed to the doGet() method.
Most operations that involve forms use either a GET or a POST operation, so for most
servlets override either doGet() or doPost().
Implementing both methods is a good practice to provide both input types or pass the request
object to a central processing method.
Difference between HTTP doGet and HTTP doPost methods of Servlet
URL Pattern Query string or form data is Form name-value pairs are sent in the
simply appended to the URL as body of the request, not in the URL
name-value pairs. itself.
Parameter passing The form elements are passed to The form elements are passed in the
the server by appending at the body of the HTTP request.
end of the URL.
Size The parameter data is limited Can send huge amount of data to the
(the limit depends on the server.
container normally 4kb)
Usage Generally used to fetch some Generally used to process the sent data.
information from the host.
Security Not Safe - A person standing Safe - No one will be able to view what
over your shoulder can view data is getting submitted (Data hidden
your userid/pwd if submitted from users.)
via Get (Users can see data in
address bar.)
Data Format Supports ASCII. Supports ASCII + Binary.
Steps to make your Java Servlet Working:
1. Use the IDE Or notepad, for writing, debugging and compiling your servlet. Once you had
compiled your servlet successfully, a class file named MyServlet.class will be generated .
2. Copy the compiled MyServlet.class file generated to the following tomcat web server
directory
C:\tomcat\webapps\examples\web-inf\classes
It should give the output Welcome to the World of Java Servlets on to the screen.
Solution:
Step1: We have to accept a user name from an HTML page. So create an HTML page as
<html>
<head><title>Program 10a</title></head>
<body bgcolor=blue>
<br><br>
</center>
</form>
</body>
</html>
Step2: Save this file as say greeting.html in the following specified path of the tomcat web server
C:\tomcat\webapps\examples\servlets
Step3: Write the following servlet using Note pad/Dos Edit
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class GreetingServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException, ServletException
{
res.setContentType("text/html"); //set the type of the response
PrintWriter out=res.getWriter(); //getting hold of a handle to write into the output
// stream
String name = req.getParameter(“name”); // access the value entered in the text
out.println(“<body bgcolor=wheat><h2>”);
}
}
2) Program to change the background color of the page based on the color
Solution: Here also our intention is to accept a color from the user and make it the background
Step1: We have to accept a color from an HTML page. So create an HTML page as
<html>
<head><title>Program 10b</title></head>
<body bgcolor=blue>
<br><br>
</center>
</form>
</body>
</html>
Step3: Write the following servlet using Note pad/Dos Edit to process the request
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
}
}
Solution:
File Description
AddCookie.html Allows a user to specify a name & value for the cookie
<html>
<body>
<center>
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String name=request.getParameter(“name”);
String data=request.getParameter(“data”);
response.addCookie(cookie);
response.setContentType(“text/html”);
pw.close();
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Cookie[] cookies=request.getCookies();
response.setContentType(“text/html”);
PrintWriter pw=response.getWriter();
pw.println(“<b>”);
String name=cookies[i].getName();
String value=cookies[i].getValue();
pw.close();
4. Program to create session and display session information viz, session ID, creation time and last
accessed.
Solution: This is another way to handle sessions. Here we try to get the current session first. If there is no
session currently, server will automatically create a session when you request. You request the session as
Program Steps:
Step 1: Create the following servlet using any text editor and save the file as, say
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");