Module 4 (Servlets)
Module 4 (Servlets)
1. What are Servlets? Briefly explain the applications of Servlets in web programming.
→ Servlet is a java class ie designed to respond with dynamic content to client request over a network.
→ Servlets are small programs that execute on the web server
→ The applications of Servlets in web programming are
i. The web page is based on the data submitted by the user.
Ex: Result pages from search engines are generated this way.
ii. The data changes frequently.
Ex: news websites, weather report
iii. The web pages uses information from corporate databases or other such sources.
Ex: You would use this for making a webpage at an online store that lists current items and
number of items in the stack.
2. List out the difference between CGI and servlets or How servlets are better in comparision
with CGI?
CGI Servlets
It is a process based ie for every request a new It is a thread based ie for every request new
process will be created & that process is thread will be created & that thread is
responsible to generate required responses responsible to generate required response
Two process never share common address All the threads share the same address space,
space, hence there is no chance of occurring hence concurrence problem is very common in
concurrence problems in CGI Servlets
We can write CGI program in variety of
We can write Servlet only in Java
languages, but most popular language is perl
Most of CGI languages are platform dependent Java language is platform independent
3. Explain the lifecycle of the servlet OR Explain the different stages in life-cycle of a servlet
API’s OR Explain the servlet lifecycle with example OR What are the phases of servlet
lifecycle? Give an example
service method()
→ This method is called for the each request.
→ This is the entry point for the every servlet request and here we have to write our own business
logic.
→ This method takes ServletRequest and ServletResponse as the parameter
→ If you override service() method its your responsibility to call the appropriate methods.
destroy method()
→ This method is called once for an instance.
→ It is used for releasing any resources used by the servlet instance (it could be datbase
connections, i/o operations etc)
→ It is called from the container when it is removing an object from the servlet container
→ Servlet instance is deleted only when the web server issues shut down or the instance is not
need for a long time
Example for Servlet life cycle
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class ServletLifeCycle extends GenericServlet {
public ServletLifeCycle()
{ System.out.println("Am from default constructor"); }
public void init(ServletConfig config)
{ System.out.println("Am from Init method...!"); }
public void service(ServletRequest request,ServletResponse response)
throws ServletException,IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("I am from doGet method");
pw.close(); }
public void destroy()
{ System.out.println("Am from Destroy methods"); }
}
→ 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 we need to
create and execute servlets.
→ When you install Tomcat software, it’s default location would be C:\Program Files\Apache
Software Foundation\Tomcat 5.5\
→ Before ececuting servlet programs, at the background we need to start Tomcat by clicking
✓ Start Menu->All Programs->Apache Tomcat->Start Tomcat
→ After executing the servlets, you can stop the Tomcat by clicking
✓ Start Menu->All Programs->Apache Tomcat->Stop Tomcat
→ 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 your CLASSPATH environment variable so that it
includes
✓ C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\servlet-api.jar
→ After you compile a servlet program, you get a .class file which has to be copied in the below path
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\
WEB-INF\classes
→ Add the servlets name & mappings to the proper web.xml file in the following directory
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\WEB-INF
✓ For instance, assuming the first example, called HelloServlet, you will add the following
lines in the section that defines the servlets:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
✓ Next, you will add the following lines to the section that defines the servlet mappings.
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
→ Copy the html file(which includes a call to your servlet program) in the below path
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\WEB-INF
5. Briefly explain java servlet program to print “Hello World” and describe the steps
involved in the execution of this servlets.
→ A simple servlet program that is going to display a string Hello World within the display area
(web page) of a browser
import java.io.*; import javax.servlet.*;
→ Next you will add the following lines to the section that defines the servlet-mappings
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
→ Create an HTML file which encapsulates a call to servlet program. Copy that HTML file in
the below path
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples\WEB-INF
→ Start Tomcat
→ Start a web browser and request the URL as shown below to view the output
http://localhost:8080/ servlets-examples/servlet/HelloServlet
6. Write a program using servlet which contains HTML page to accept username and display
greeting message as “Hello World” in the browser window OR Write a Java Servlet to
read name from client page & say Hello World to the name as response OR Write a
program to describe parameter reading using servlets OR Describe the simple HTML file
to pass the parameter to servlet & display the parameter values accepted by a servlet.
Username.html
<html>
<body>
<form method="post“ action="http://localhost:8080/servlets-examples/servlet/Username">
Username: <input type=text name="username" size="25”>
<input type=submit value="Submit">
</form>
</body>
</html>
Username.java
import java.io.*; import java.util.*; import javax.servlet.*;
public class Username extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
String username=request.getParameter(“username”);
pw.println(“name is”+username);
pw.close(); } }
OR
Username.html
<html>
<body>
<form method="post“ action="http://localhost:8080/servlets-examples/servlet/Username">
Username: <input type=text name="username" size="25”>
<input type=submit value="Submit">
</form>
</body>
</html>
Username.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class Username extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
String username=request.getParameter(“username”);
pw.println(“name is”+username);
pw.close();
} }
OR
Username.html
<html>
<body>
<form method="post“ action="http://localhost:8080/servlets-examples/servlet/Username">
Username: <input type=text name="username" size="25”>
<input type=submit value="Submit">
</form>
</body>
</html>
Username.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class Username extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Dept.of ISE, KIT, Tiptur Naveen N Page 6
Module-4: Servlets & JSP
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
String username=request.getParameter(“username”);
pw.println(“name is”+username);
pw.close();
} }
7. What is a cookie? What is the use of Cookie? List out the methods defined by a cookie.
Write a program to add cookie.(10) OR Write a short note on Cookies OR Explain the use
of Cookies with program OR Explain how the Cookies are created using Java Servlet OR
Explain the working of cookie in java with code snippets OR Explain the various Cookie
attributes
→ A cookie is a small piece of information created by a servlet program that is stored on the
client’s hard disk by the browser.
→ Cookies are used to keep track of user activities on a client machine
Ex: Assume that a user visits an online store. A cookie can save the user’s name, address, and
other information. The user does not need to enter this data each time he or she visits the store.
→ 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.
→ 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.
❖ Advantages of cookies
1. Simplest technique of maintaining the state
2. Cookies are maintained at client side
❖ Disadvantages of cookies
1. It will not work if cookie is disabled from the browser
2. Only textual information can be set in cookie object
❖ Methods defined by cookie
Method Description
Public String getName() Returns the name of the cookie. The name can’t be changed after
creation
Dept.of ISE, KIT, Tiptur Naveen N Page 7
Module-4: Servlets & JSP
8. What is session tracking? List out the methods defined by HttpSession. With a code
snippet, explain how session tracking is handled in java with servlets OR Illustrate the use
of session information in servlets OR Write a short note on Session Tracking
→ Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
→ It is a mechanism to save state information so that information can be collected from several
interactions between browser and server
→ HTTP is stateless that means each request is considered as the new request.
→ 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.
❖ Methods defined by HttpSession
Method Description
Void removeAttribute(String attr) Removes the attribute specified by attr from the session
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();
Date date = (Date)hs.getAttribute("date");
if(date != null)
{
pw.print("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date(); hs.setAttribute("date", date);
pw.println("Current date: " + date);
} }
9. Develop a simple servlet program that handles the Http requests and responses OR Write
a short note on Http Request and response
→ The HttpServlet class provides specialized methods that handle the various types of HTTP
requests.
The HttpServletRequest Interface
→ The HttpServletRequest interface enables a servlet to obtain information about a client request
Method Description
Cookie[ ] getCookies( ) Returns an array of the cookies in this request.
String getMethod( ) Returns the HTTP method for this request.
HttpSession getSession( ) Returns the session for this request. If a session does not exist,
one is created and then returned.
String getQueryString( ) Returns any query string in the URL.
The HttpServletResponse Interface
The HttpServletResponse interface enables a servlet to formulate an HTTP response to a
client.
Method Description
void addCookie(Cookie cookie) Adds cookie to the HTTP response
void sendError(int c)throws IOException Sends the error code c to the client.
void sendError(int c, String s)throws IOException Sends the error code c and message s to the client.
void sendRedirect(String url)throws IOException Redirects the client to url.
→ A servlet developer typically overrides one of these methods. These methods are doDelete( ),
doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ).
The GET and POST requests are commonly used when handling form input.
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<input type=submit value="Submit">
</form>
</body>
</html>
color.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class color 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();
} }
10. List and explain the 3 methods that are automatically called when a JSP is requested &
terminated normally
→ JSP is a server side program that is similar in design & functionality to a java servlet.
→ A JSP is simpler to create than a Java servlet because JSP is written in HTML rather than in a
Java programming language. JSP infact is converted to a Java servlet the first time that a client
requests the JSP.
→ There are 3 methods of the JSP which are automatically called. They are
1. jspinit() method
2. jspservice() method
3. jspdestroy() method
The jspinit(), which is similar to the init method in the javax.servlet.Servlet interface, is
called when the JSPPage object is created & can be used to run some initialization. This
method is called only once during the life cycle of the JSP page the first time the jsp page is
invoked.
The jspdestroy() method is analogous with the destroy method of the javax.servlet.Servlet
interface. This method is called before the jsp servlet object is destroyed. You can use this
method to do some clean up if you want.
The jspservice() method is called by the jsp container to generate the content of the jsp page
or jspservice() method is automatically called when called it retrieves a connection to Http
11. Explain different types of JSP tags with an example. OR Briefly explain the 5 types of JSP
tags that are used in any JSP program with program OR what are the different types of
JSP tags? Demonstrate with a simple program
<%!int marks=70;%>
<%if(marks>70){%>
Your Marks=<%=marks%> and your grade is A
<%}else{%>
Your Marks=<%=marks%> and your grade is B
<%}%>
</body>
</html>
→ Java variables & objects that are used in a jsp program must be declared using the same
coding technique as used in java. However the declaration statement must appear in a jsp tag
within the jsp program
<html> <body>
<%! int age=29; %>
<p> your age is <% =age %> </p>
</body> </html>
→ Multiple variables can be declared within a single jsp tag as shown below
<html> <body>
<%! int age=29; float salary; int empnumber; %>
</body> </html>
→ A method is defined similar to how a method is defined in java. However the method
definition must be placed within the jsp tag.
<html> <body>
<%! int curve(int grade) { return 10+grade; } %>
<p> your curved grade is: <%=curve(80) %> </p>
</body> </html>
→ Methods can also be overloaded as shown below
→ <html> <body>
<%! int curve(int grade) {
return 10+grade; }
int curve(int grade, int curvevalue) {
return curvevalue+grade; } %>
<p> your curved grade is: <% =curve(80, 10) %> </p>
<p> your curved grade is: <% =curve(70) %> </p>
</body>
</html>
→ The browser generates a user request string whenever the submit button is selected. The user
request string consists of the URL & the query string.
→ A typical user request string is as shown below
http://localhost:8080/examples/servlet/colorgetServlet?color=green
→ The JSP program needs to parse the query string to extract values of fields that are to be
processed by the program. This can be done using the JSP request object.
→ The getParameter(Name) : is the method used to parse a value of the specified field. The
getParameter() method requires an argument which is the name of the fields whose value is
to be retrieved.
→ There are 4 predefined implicit objects that are in every JSP program. These are request,
response, session and out.
1. The request object is an instance of HttpServletRequest
2. The response object is an instance of HttpServletResponse
3. The session object is an instance of HttpSession
4. The out object is an instance of JSPWriter that is used to send a response to the client.
→ Copying values from multivalued fields can be performed using getParameterValues()
method as shown below
<%! String[] email=request.getParameterValues(“eaddr”); %>
<%=email[0]; %> <%=email[1]; %>
In the above example, eaddr contains many email addresses which would be stored into the
array called email.
14. Write a JSP to create and read cookie named userID that stores the value KI007
</body>
</html>
17. Explain the 2 types of control statements used in JSP by taking suitable examples
→ One of the most powerful features available in JSP is the ability to change the flow of the
program to truly create dynamic content for a web page based on conditions received from the
browser
→ There are 2 control statements used to change the flow of a JSP program. These are the if
statement and the switch statement, both of which are also used to direct the flow of a Java
program
→ The if statement evaluates a condition statement to determine if one or more lines of code are
to be executed or skipped
→ Similarly a switch statement compares a value with one or more other values associated with a
case statement. The code segment that is associated with the matching case statement is
executed. Code segments associated with other case statements are ignored
if-else example
<html> <body>
<%! int grade=70;%>
<% if(grade>69) { %>
<p>you passed </p>
<%} else {%>
<p> better luck next time </p>
<% } %>
Dept.of ISE, KIT, Tiptur Naveen N Page 17
Module-4: Servlets & JSP
</body>
</html>
switch example
<html>
<body>
<%! int grade=70;%>
<% switch(grade) {
case 90:%>
<p> your final grade is a A </p>
<% break;
case 80: %>
<p> your final grade is a B </p>
<% break;
case 70: %>
<p> your final grade is a C </p>
<% break;
case 60: %>
<p> your final grade is a D </p>
<% break;
} %>
</body> </html>
18. Explain the 3 types of loops used in JSP by taking suitable examples
→ JSP loops are nearly identical to loops that you use in your Java program except you can
repeat HTML tags and related information multiple times within your JSP program without
having to enter the additional HTML tags
→ There are 3 kinds of loops commonly used in a Java program. These are the for loop, the while
loop and the do while loop.
→ The for loop repeats usually a specified number of times although you can create an endless
for loop
→ The while loop executes continually as long as specified condition remains true. However the
while loop may not execute because the condition may never be true
→ The do while loop executes at least once; afterwards the conditional expression in the do while
loop is evaluated to determine if the loop should be executed another time
for loop example
<html>
<body>
<%! int[] grade={100,82,93}; int x=0; %>
<table> <tr>
<td>First</td> <td>Second</td> <td>Third</td>
</tr>
<tr>
<% for(int i=0;i<3;i++) { %>
<td><%=grade[i]%></td>
<%}%>
</tr> </table>
</body>
</html>
<% x++;
} while(x<3); %>
</tr> </table>
</body> </html>
19. Write a program using servlet which contains HTML page with various color options.
When user choose 8 the particular color, the background of that page should be changed
accordingly
Bgcolor.html
<html>
<body>
<form action="http://localhost:8080/servlets-examples/servlet/Bgcolor">
<b> color</b>
<select name="data" size="1">
<option value="red">6</option>
<option value="green">7</option>
<option value="blue">8</option>
</select>
<input type=submit value="Submit">
</form>
</body>
</html>
Bgcolor.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class Bgcolor extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String data = request.getParameter("data");
if(data.equals("red"))
out.println("<body bgcolor=red>"+data);
else if(data.equals("green"))
out.println("<body bgcolor=green>"+data);
else if(data.equals("blue"))
out.println("<body bgcolor=blue>"+data);
}}
20. Department has set the grade for the subject java as follows:
Above 90=A, 80-89=B, 70-79=C, Below 70=fail.
Sham enters his marks for the subject java in the interface provided. Write a JSP
program to accept the marks entered and display his grade to the browser
Marks.html
<html>
<body>
<form action="http://localhost:8080/servlets-examples/servlet/Marks.jsp" method="post">
Marks:<input type="text" name="marks" size="3"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Marks.jsp
<html>
<body>
<% String marks=request.getParameter("marks");
int mark=Integer.parseInt(marks);%>
<%if(mark>90){%>
<p>your grade is A <%}
else if(mark>80 & mark<89) { %>
<p>your grade is B<%}
else if(mark>70 & mark<79) {%>
<p>your grade is C <%}
else if(mark<70){%>
<p>you are fail<%}%>
</body>
</html>
21. Write a JAVA servlets which reads 2 parameters from the webpage, say value 1 and value
2, which are of type integers, and finds the sum of the 2 values, and return back the result
as a webpage
Integer.html
<html>
<body>
Dept.of ISE, KIT, Tiptur Naveen N Page 21
Module-4: Servlets & JSP
22. List and explain core classes that are provided in javax.servlet package.
→ javax.servlet package contain the classes and interfaces that are required to build servlets.
→ However this package do not form a part of Java’s core packages. Instead they are standard
extensions provided by Tomcat.
javax.servlet package
Interfaces
Interface Description
Class Description
23. List and explain core classes that are provided in javax.servlet.http package.
→ javax.servlet.http package contain the classes and interfaces that are required to build servlets.
→ However this package do not form a part of Java’s core packages. Instead they are standard
extensions provided by Tomcat.
javax.servlet.http package
Interfaces
Class Description
Class Description