module-4
module-4
1. What Is a Servlet?
Page 1
2. Servlet Architecture:
• The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet container.
• The servlet container loads the servlet before invoking the service() method.
• Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the
servlet.
• User sends request for a servlet by clicking a link that has URL to a servlet.
• The container finds the servlet using deployment descriptor and creates two objects
HttpServletRequest
HttpServletResponse
• Then the container creates or allocates a thread for that request and calls the Servlet's service()
method and passes the request, response objects as arguments.
• The service() method, then decides which servlet method, doGet() or doPost() to call, based
on HTTP Request Method(Get, Post etc) sent by the client. Suppose the client sent an HTTP
GET request, so the service() will call Servlet's doGet() method.
• Then the Servlet uses response object to write the response back to the client.
Page 2
• After the service() method is completed the thread dies. And the request and response objects
are ready for garbage collection.
Page 3
public void init() throws ServletException
{
// Initialization code...
}
The service() method :
• The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.
• Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service() method checks the HTTP request type (GET, POST,
PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as
appropriate.
• Here is the signature of this method:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{
}
• The service () method is called by the container and service method invokes doGe,
doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with
service() method but you override either doGet() or doPost() depending on what type
of request you receive from the client.
• The doGet() and doPost() are most frequently used methods with in each service
request. Here is the signature of these two methods.
The destroy() method :
• The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities.
• After the destroy() method is called, the servlet object is marked for garbage
collection. The destroy method definition looks like this:
public void destroy()
Page 4
{
// Finalization code...
}
imort javax.servlet.*;
class className extends GenericServlet
{
public void init() throws ServletException
{
// Initialization code...
}
public void service(ServletRequest request, ServletResponse response)throws
ServletException, IOException
{
}
public void destroy()
{
// Finalization code...
}
}
Page 5
Class Room Session 1 Review Questions
What is Servlet
What is Applet
What are different method in servlet Life Cycle.
Class Room Session 2
5. Simple Servlet program:
import java.io.*;
import javax.servlet.*;
public class A extends GenericServlet
{
public void service(ServletRequest req ,ServletResponse res)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
out.println(“<p> My First Servlet program </p> “);
}
}
Web deployment: (web.xml)
<servlet>
<servlet-name>CSA</servlet>
<servlet-class>A.class</sertlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CSA</servlet>
<url-patter>*.dll</url-patter> </servlet-mapping>
6. servlet API:
javax.servlet - The javax.servlet package contains a number of classes and interfaces that
describe and define the contracts between a servlet class and the runtime environment
provided for an instance of such a class by a conforming servlet container.
javax.servlet.http-The javax.servlet.http package contains a number of classes and
interfaces that describe and define the contracts between a servlet class running under the
HTTP protocol and the runtime environment provided for an instance of such a class by a
conforming servlet container
Page 6
7. The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes that
establish the framework in which servlets operate.
Page 7
8. The javax.servlet.http Package
The javax.servlet.http package contains a number of interfaces classes that are commonly
used by servlet developers.
• 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.
Page 8
• Different mathods to read parameter are as follows:
• getParameter(string)
• getParamaterNames();
• getParamaterValues();
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class Simple extends HttpServlet
{
public void doGet(HttpServletRequest req ,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
String msg=req.getParameter("t1");
out.println(“hello”+msg+”how are you”);
}
}
HTML code
<html>
<body>
<form action=”A” >
<input type=”text box” name=”t1” value=” “>
<input type=”submit” value=”submit”>
</form> </body> </html>
Page 9
using getParameterName() method:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class Simple extends HttpServlet
{
public void doGet(HttpServletRequest req ,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
Enumeration e=req.getParameterNames();
while(e.hasMoreElements())
{
Sting a=(String)e.nextElement();
String msg=request.getParameter(a);
out.println(msg);
}
}
<html>
<body>
<form action=”Simple”>
<input type=”text box” name=”t1” value=” “>
<input type=”text box” name=”t2” value=” “>
<input type=”submit” value=”submit”>
</form>
</body>
</html>
Page 10
getParameterValues():
• Returns an array of String objects containing all of the values the given request parameter has, or
null if the parameter does not exist.
• If the parameter has a single value, the array has a length of 1.
• method getParameterValues() will generally came into picture if there is a chance of getting multiple values
for any input parameter, this method will retrieve all of it values and store as string array.
Syntax
<html>
<body>
<form action="Simple" >
Skills :
<input type="checkbox" name="t1" value="JAVA">JAVA
<input type="checkbox" name="t1" value="C++">C++
<input type="checkbox" name="t1" value="Python">PYTHON
<input type="submit" value="Submit">
</form>
</body>
</html>
Simple.java
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class Simple extends HttpServlet
{
public void doGet(HttpServletRequest req ,HttpServletResponse res)throws
ServletException,IOException
{
PrintWriter pw=res.getWriter();
String[] values=req.getParameterValues("t1");
pw.println("Selected Values...");
for(String a:values)
pw.println(a);
}
}
Page 11
Class Room Session 2 Review Questions
What is servlet API?
What is servlet Package?
Which method is used to read servlet Parameter?
Class Room Session 3
10. Handling Http request and Http response:
• The HttpServlet class provide a specialized methods that handle the various types of
HTTP request.
• The different methods are:
doGet(),doPost(),doOperation(),doPut(),doTrace(),doDelete()
HTTP doGet() method:
• The doGet() method is the method inside a servlet that gets called every time a
request from a html or jsp page is submitted.
• The control first reaches the doGet() method of the servlet and then the servlet
decides what functionality to invoke based on the submit request. The get method
called when the type of page submission is "GET".
• doGet is used when there is are requirement of sending data appended to a query
string in the URL.
• The doGet models the GET method of Http and it is used to retrieve the info on the
client from some server as a request to it.
• The doGet cannot be used to send too much info appended as a query stream. GET
puts the form values into the URL string.
• GET is limited to about 256 characters (usually a browser limitation) and creates
really ugly URLs.
Program:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class Simple extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
Page 12
String msg=req.getParameter("t1");
out.println(“hello”+msg+”how are you”);
}
}
<html>
<body>
<form action=”Simple” method=GET >
<input type=”text box” name=”t1” value=” “>
<input type=”submit” name=”submit”>
</form>
</body>
</html>
Page 13
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
String msg=req.getParameter("t1");
out.println(“hello”+msg+”how are you”);
}
}
<html>
<body>
<form action=”Simple” method=POST>
<input type=”text box” name=”t1” value=” “>
<input type=”submit” name=”submit”>
</form>
</body>
</html>
Difference between HTTP doGet and HTTP doPost methods of Servlet
Difference Type GET (doGet()) POST (doPost())
HTTP Request The request contains only the Along with request line and header
request line and HTTP it also contains HTTP body.
URL Pattern Query string or form data is Form name-value pairs are sent in
simply appended to the URL the body of the request, not in the
as name-value pairs. URL itself.
Parameter passing The form elements are passed The form elements are passed in
to the server by appending at the body of the HTTP request.
the end of the URL.
Size The parameter data is Can send huge amount of data to
limited (the limit depends the server.
on the container normally
Idempotency GET is Idempotent(can be applied POST is not idempotent(warns if
multiple times without changing
applied multiple times without
the values
changing the values
Page 14
Usage Generally used to fetch Generally used to process the sent
some information from the data.
Security Not Safe - A person standing over Safe - No one will be able to view
your shoulder can view your
what data is getting submitted (Data
userid/pwd if submitted via Get
(Users can see data in address bar.) hidden from users.)
Page 15
9. void setMaxAge(int)-set the maximum age of cookie
10.void setSecure(Boolean)-set the secure of cookie.
Creating cookie:
• Cookie are created using cookie class constructor.
• Content of cookies are added the browser using addCookies() method.
Reading cookies:
• Reading the cookie information from the browser using getCookies() method.
• Find the length of cookie class.
• Retrive the information using different method belongs the cookie class.
Program: To create and read the cookie for the given cookie name as “EMPID” and its
value as”AN2356”.(vtu program)
public class A extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
/* creating cookie object */
Cookie c=new Cookie(“EMPID”,”AN2356”);
res.addCookie(c);//adding cookie in the response
/*reading cookies */
Cookie c[]=req.getCookies();
for(int i=0;i<c.length;i++)
{
String Name=c[i].getName();
String value= c[i].getValue();
out.println(“name=”+Name);
out.println(“Value=”+Value);
}
} }
Page 16
Class Room Session 3 Review Questions
Program:
import javax.servelt.*;
import java.io.*;
public class Simple extends HttpServlet
{
public void doGet(HttpServletRequest req ,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
Page 17
HttpSession h=req.getSesssion(true);
h.setAttribute(“UserName”,”Santosh”);
out.println(“User Name”+h.getAttribute(“UserName”));
}
}
void service(ServletRequest req, Called by the servlet container to allow the servlet to
ServletResponse res) respond to a request.
• 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:
Page 18
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
1. The examples here is Windows environment. The default location for Tomcat 5.5.17 is
C:\Program Files\Apache Software Foundation\Tomcat 5.5\
2. to set the environmental variable JAVA_HOME to the top-level directory in which
the Java Software Development Kit is installed.
3. To start Tomcat, select Start Tomcat in the Start | Programs menu, , and the n press Start in
the Tomcat Properties dialog. The directory
C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\
Contain servlet.api.jar.
4.. To make this file accessible, update your CLASSPATH environment
variable so that it includes
C:\Program Files\Apache Software Foundation\Tomcat5.5\common\lib\servlet.api.jar
5. First. Copy the servlet’s class file into the following directory:
C:\Program Files\Apache Software
Foundation\Tomcat5.5\webapps\servlets.examples\WEB-INF\classes
6. Next, add the servlet’s name and mapping to the web.xml file in the following directory
Page 19
Class Room Session 4 Review Questions
• JSP are translated and compiled into JAVA servlets but are easier to develop
than JAVA servlets.
• JSP uses simplified scripting language based syntax for embedding HTML into JSP.
• JSP containers provide easy way for accessing standard objects and actions.
• JSP reaps all the benefits provided by JAVA servlets and web container
environment, but they have an added advantage of being simpler and more natural
program for web enabling enterprise developer.
• JSP use HTTP as default request / response communication paradigm and thus
make JSP ideal as Web Enabling Technology.
Page 20
2. JSP Life cycle:
Initialization:
• When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override the jspInit()
method:
public void jspInit()
{
// Initialization code...
}
• Typically initialization is performed only once and as with the servlet init method,
you generally initialize database connections, open files, and create lookup tables in
the jspInit method.
JSP service:
• This phase of the JSP life cycle represents all interactions with requests until the JSP
is destroyed.
• Whenever a browser requests a JSP and the page has been loaded and initialized, the
JSP engine invokes the _jspService() method in the JSP.
Page 21
• The _jspService() method takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response)
{
// Service handling code...
}
• The _jspService() method of a JSP is invoked once per a request and is responsible
for generating the response for that request and this method is also responsible for
generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
JSP destroy:
• The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.
• The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy when you need to perform any cleanup, such as releasing
database connections or closing open files.
• The jspDestroy() method has the following form:
public void jspDestroy()
{
// Your cleanup code goes here.
}
3. JSP Architecture:
The following steps explain how the web server creates the web page using JSP:
• As with a normal page, your browser sends an HTTP request to the web server.
• The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp
instead of .html.
• The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
Page 22
Class Room Session 5 Review Questions
What is the full form of JSP?
What are the main components in JSP Architecture?
What are the advantages of JSP?
Class Room Session 6
statements and all JSP elements are converted to Java code that implements the
corresponding dynamic behavior of the page.
• The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
• A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format, which the
servlet engine passes to the web server inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static
HTML content.
• Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page
Page 23
Directive Tag:
A Directive tag opens with <%@ and closes with %>. There are three commonly used
directives.Used to import java packages into JSP program
Example:
Expression Tag:
• A JSP expression element contains a scripting language expression that is
evaluated, converted to a String, and inserted where the expression appears in the
JSP file.
• Because the value of an expression is converted to a String, you can use an expression
within a line of text, whether or not it is tagged with HTML, in a JSP file.
• The expression element can contain any expression that is valid according to
the Java anguage Specification but you cannot use a semicolon to end an expression.
Page 24
Syntax two forms:
<%= expr %>
example:
<%! int a = 5, b = 10; %>
<%= a+b %>
Scriptlet Tag:
A scriptlet tag opens with <% and contains commonly used java control statements and
loops. It closes with %>
Syntax two forms:
<% control statements %>
Example:
<% for (int i = 0; i < 2; i++)
{
out.println(“value of I”+i);
}
%>
Program to display the grading system for the given java subject marks using control
statements (VTU question VIMP):
<%
int marks=65;
if(marks>=90)
out.println(“GRADE A”);
else if(marks>=80 && marks<=89)
out.println(“GRADE B”);
else if(marks>=70 && marks<=79)
out.println(“GRADE C”);
else
out.println(“FAIL”);
%>
Page 25
6. Request String:
• The browser generates a user request string whenever the submit button is selected.
• The HttpServletRequest parameter Request object has a request scope that is used to
access the HTTP request data, and also provides a context to associate the request-
specific data.
• Request object implements javax.servlet.ServletRequest interface.
• Jsp provides the two ways of request string:
getParameter(String)
getParameterNames()
getParameterValues();
Using request.getParameter()
getParameter() method requires an argument, which is the name of the field whose
value you want to retrieve.
Program: Department has set the grade for java subject,accept the input from the user and
display the grading on the browser. (VTU question VIMP)
above 90-grade A
80-89 grade B
70-79 grade C
below 70 Fail using jsp
A.html
<html>
<body>
<form action=A.jsp>
<input type=”textbox” name=”t1” value=” “>
<input type=”submit” mane=”submit”>
</form>
</body>
</html>
Page 26
A.jsp
<%
String t = request.getParameter(“t1”);
int marks=Integer.parseInt(t);
if(marks>=90)
out.println(“GRADE A”);
else if(marks>=80 && marks<=89)
out.println(“GRADE B”);
else if(marks>=70 && marks<=79)
out.println(“GRADE C”);
else
out.println(“FAIL”)
%>
Page 27
using getParameterNames():
getParameterNames()-returns an enumeration of the parameter names. These are processed in
loop
program:
<html>
<body>
<form action=Simple.jsp>
Name:<input type=”textbox” name=”Name” value=” “>
USN:<input type=”textbox” name=”Usn” value=” “>
Marks:<input type=”textbox” name=”Marks” value=” “>
<input type=”submit” mane=”submit”>
</form>
</body>
</html>
Syntax
6. cookies:
• A cookie is a small piece of information created by a JSP program that is stored in
the client’s hard disk by the browser. Cookies are used to store various kind of
information such as username, password, and user preferences, etc.
• Different methods in cookie class are:
1. String getName()- Returns a name of cookie
2. String getValue()-Returns a value of cookie
3. int getMaxAge()-Returns a maximum age of cookie in millisecond
4. String getDomain()-Returns a domain
5. boolean getSecure()-Returns true if cookie is secure otherwise false
6. String getPath()-Returns a path of cookie
7.void setPath(Sting)- set the path of cookie
8.void setDomain(String)-set the domain of cookie
9.void setMaxAge(int)-set the maximum age of cookie
10.void setSecure(Boolean)-set the secure of cookie.
Page 29
Creating cookie:
Cookie are created using cookie class constructor.
Content of cookies are added the browser using addCookies() method.
Reading cookies:
Reading the cookie information from the browser using getCookies() method.
Find the length of cookie class.
Retrive the information using different method belongs the cookie class
PROGRAM: To create and read the cookie for the given cookie name as “EMPID”
and its value as”AN2356”.(VTU question VIMP)
<%
Cookie c[]=request.getCookies();
for(i=0;i<c.length;i++)
{
String name=c[i].getName();
String value=c[i].getValue ();
out.println(“name=”+name);
out.println(“value=”+value);
}
%>
Page 30
Class Room Session 6 Review Questions
List some of the JSP tags.
Define cookies with reference to JSP.
Class Room Session 7
7. Session object(session tracking or session uses)
Program:
<%
HttpSession h=request.getSesssion(true);
h.setAttribute(“UserName”,”Santosh”);
out.println(“User Name”+h.getAttribute(“UserName”));
%>
Page 31
Class Room Session 7 Review Questions
Mention two differences between JSP and servlets
What is the role of Tomcat server
Module4 Question Bank