[go: up one dir, main page]

0% found this document useful (0 votes)
17 views23 pages

Module 4 (Servlets)

The document provides an overview of Servlets and JSP, detailing their applications, lifecycle, and the differences between CGI and Servlets. It explains how to configure the Tomcat web server for servlet development, demonstrates simple servlet programs, and discusses cookies and session tracking in Java. Additionally, it includes code snippets for creating and managing servlets and cookies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views23 pages

Module 4 (Servlets)

The document provides an overview of Servlets and JSP, detailing their applications, lifecycle, and the differences between CGI and Servlets. It explains how to configure the Tomcat web server for servlet development, demonstrates simple servlet programs, and discusses cookies and session tracking in Java. Additionally, it includes code snippets for creating and managing servlets and cookies.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Module-4: Servlets & JSP

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

Servlet life cycle has following methods.


1) init() 2) service() 3) destroy()
init() method
→ This method is called once for a servlet instance.
→ When first time servlet is called, servlet container creates an instance of that servlet and
loaded into the memory. Future requests will be served by the same instance(object) without
creating the new instance.

Dept.of ISE, KIT, Tiptur Naveen N Page 1


Module-4: Servlets & JSP

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"); }
}

4. Describe in detail how tomcat webserver is configured for development of servlet. OR


What is the role of Tomcat for servlet development? Explain the steps involved in
configuring Tomcat webserver.

→ 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.

Dept.of ISE, KIT, Tiptur Naveen N Page 2


Module-4: Servlets & JSP

→ 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.*;

Dept.of ISE, KIT, Tiptur Naveen N Page 3


Module-4: Servlets & JSP

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("Hello World");
pw.close();
} }
 The javax.servlet package has the classes and interfaces required to build servlets
 HelloServlet is a sub class of GenericServlet
 The GenericServlet class provides init(), service() and destroy() methods. In this program,
default version of init() and destroy() is available and we are overriding service() method.
 The service() method which is overridden handles requests from clients.
 Service() method has 2 parameters
1) ServletRequest object – which enables the servlet to read data that is provided via the
client request
2) ServletResponse object – which enables the servlet to formulate a response for the client
 setContentType() – specifies whether the output to be displayed is a simple plain text or html
 getWriter() method is used to get an object of PrintWriter object. Anything written to this
stream is sent to the client as a part of the HTTP response
 PrintWriter converts java’s unicode character to local specific encoding
 PrintWriter object is used with println() method to display the desired data within the web
page
→ Create a servlet program using notepad with filename.java and save it in jdk/bin directory
→ Compile the servlet program as shown below
javac filename.java
→ Once you successfully compile, you get filename.class file. Copy the .class file in the below path
C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\servlets-examples
\WEB-INF\classes
→ Add the servlets name and 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
Here filename as 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>

Dept.of ISE, KIT, Tiptur Naveen N Page 4


Module-4: Servlets & JSP

→ 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(); } }

Dept.of ISE, KIT, Tiptur Naveen N Page 5


Module-4: Servlets & JSP

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

Public String getValue() Returns the value of the cookie


Public void setName(String name) Changes the name of the cookie
Public void setValue(String value) Changes the value of the cookie
Public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds
AddCookie.html
<html>
<body>
<form method="post“ action="http://localhost:8080/servlets-examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=text name="data" size=25 >
<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(); } }
GetCookieServlet.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();

Dept.of ISE, KIT, Tiptur Naveen N Page 8


Module-4: Servlets & JSP

for(int i = 0; i < cookies.length; i++) {


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

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

String getId() Returns the session ID


Void invalidate() Invalidates this session and removes it from the client
Object getAttribute(String attr) Returns the value associated with the name passed in attr.
Void setattribute(String attr, Object val) Returns null
Associates if attrpassed
the value is notinfound
val with the attribute name passed in attr.

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);

Dept.of ISE, KIT, Tiptur Naveen N Page 9


Module-4: Servlets & JSP

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.

Dept.of ISE, KIT, Tiptur Naveen N Page 10


Module-4: Servlets & JSP

Handling HTTP GET Requests


color.html
<html>
<body>
<form method=“get" action="http://localhost:8080/servlets-examples/servlet/color">
Color: <select name="color" size="1">
<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 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();
} }
→ The URL sent from the browser to the server is
http://localhost:8080/servlets-examples/servlet/ColorGetServlet?color=Red
The characters to the right of the question mark are known as the query string.
OR
Handling HTTP POST Requests
color.html
<html>
<body>
<form method="post" action="http://localhost:8080/servlets-examples/servlet/color">
Color: <select name="color" size="1">
Dept.of ISE, KIT, Tiptur Naveen N Page 11
Module-4: Servlets & JSP

<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.

Dept.of ISE, KIT, Tiptur Naveen N Page 12


Module-4: Servlets & JSP

 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

→ A JSP program consists of a combination of HTML tags & JSP tags


→ The JSP tags contains the java code which is to be executed before the output of the JSP
program is sent to the browser.
→ There are 5 types of JSP tags in a JSP program. They are
1. Comment tag=> A comment tag opens with <% ---- and closes with ------%> & is
followed by a comment that usually describes the functionality of statements.
Eg: <%----JSP tag-----%>
2. Declaration statement tag=> A declaration tag opens with <%! and closes with %> and is
followed by java declaration statements that define variables, objects & methods that are
available to other components of the JSP program.
Eg: <%! int age=29; %>
3. Directive tag=> A directive tag opens with <%@ and closes with %>. This is used to direct
the JSP virtual engine to perform a specific task such as importing a java package required.
Eg: <%@page import=“java.util.*”; %>
4. Expression tag=> A expression tag opens with <%= and closes with %> and is used for an
expression statement.
Eg: <% =age %>
5. Scriplet tag=> A scriplet tag opens with <% and closes with %> and contains commonly
used java control statements and loops.
Eg: <% if(grade>69) { %>
<p> you passed </p>
<% } %>
Program to show all the tags
<html>
<body>
<%@page import="javax.servlet.*,javax.servlet.http.*;"%>

Dept.of ISE, KIT, Tiptur Naveen N Page 13


Module-4: Servlets & JSP

<%!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>

12. Write a note on variables and methods in JSP

→ 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>

Dept.of ISE, KIT, Tiptur Naveen N Page 14


Module-4: Servlets & JSP

</html>

13. Write a note on request string

→ 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

→ A cookie can be created as shown below


<html>
<body>
<%@ page import="java.util.*,javax.servlet.*,javax.servlet.http.*" %>
<%! Cookie cookie=new Cookie("userID","KI007"); %>
<% response.addCookie(cookie); %>
</body>
</html>
→ A cookie can be retrieved and read as shown below
<html>
<body>
Dept.of ISE, KIT, Tiptur Naveen N Page 15
Module-4: Servlets & JSP

<%@ page import="java.util.*,javax.servlet.*,javax.servlet.http.*" %>


<%! String CName, CValue; %>
<% Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++)
{
CName=cookies[i].getName();
CValue=cookies[i].getValue();
}
<p>Cookie Name=<%= MyCookieName %>
<p>Cookie Value=<%= MyCookieValue %>
</body>
</html>

15. What is a session? Explain how to create session using JSP

→ In JSP, session is an implicit object of type HttpSession.


→ Each time a session is created, a unique ID enables JSP programs to track multiple sessions.
→ A session attribute can be created as shown below
<html>
<body>
<%@ page import="java.util.*,javax.servlet.*,javax.servlet.http.*" %>
<%! String name="userID", value="1234"; %>
<% session.setAttribute(name,value);%>
</body>
</html>
→ An attributes can be read each time the page opens as follows
<html>
<body>
<%@ page import="java.util.*,javax.servlet.*,javax.servlet.http.*" %>
<% Enumeration purchases=session.getAttributeNames();
while(purchases.hasMoreElements()) {
String name=(String)purchases.nextElement();
String value=(String)session.getAttribute(name);
%>
<p>Attribute Name=<%= name%></p>
<p>Attribute Value=<%= value%></p>
<%}%>

Dept.of ISE, KIT, Tiptur Naveen N Page 16


Module-4: Servlets & JSP

</body>
</html>

16. Write the difference between JSP and Servlets.


1. A JSP can only support Http protocol but a servlet can support protocol like SMTP, FTP &
Http etc.
2. Servlets are pure java programs here we can’t use HTML but in JSP we use HTML, so we
can use and modify the data very easily.
3. In Servlets both the presentation & business logic are place it together where as in JSP both
are seperated by defining java beans.
4. JSP page automatic compile but Servlet will manually redeploy.
5. Servlets are faster than JSP because while running JSP program it will be converted into
Servlets & then executed, so it takes more time.
6. A JSP is typically oriented towards displaying information & a Servlet is more oriented
towards processing information.
7. In ModelViewController, JSP acts as a view & Servlet acts as a controller.

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

Dept.of ISE, KIT, Tiptur Naveen N Page 18


Module-4: Servlets & JSP

<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>

while 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>
<% while(x<3) { %>
<td><%=grade[x]%></td>
<% x++;
}%>
</tr> </table>
</body> </html>

do-while 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> <% do { %>
<td><%=grade[x]%></td>

Dept.of ISE, KIT, Tiptur Naveen N Page 19


Module-4: Servlets & JSP

<% 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);

Dept.of ISE, KIT, Tiptur Naveen N Page 20


Module-4: Servlets & JSP

}}

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

<form action="http://localhost:8080/servlets-examples/servlet/Integer" method="post">


Integer1: <input type="text" name="value1" size="3">
Integer1: <input type="text" name="value2" size="3">
<input type="submit" value="submit">
</form>
</body> </html>
Integer.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class Integer extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html"); PrintWriter out = response.getWriter();
String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");
int i1=Integer.parseInt(value1); int i2=Integer.parseInt(value2);
int i3=i1+i2;
out.println(“Sum of 2 numbers=”+i3);
out.close();
}}

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

Servlet Declares life-cycle methods for a servlet


ServletConfig Allows servlets to get initialization parameters
ServletContext Enables servlets to log events and access information about their environment
ServletRequest Used to read data from a client request
ServletResponse Used to write data to a client response
 Classes

Class Description

GenericServlet Implements the servlet and servletconfig interfaces

Dept.of ISE, KIT, Tiptur Naveen N Page 22


Module-4: Servlets & JSP

ServletInputStream Provides an input stream for reading requests from a client


ServletOutputStream Provides an output stream for writing responses to a client
ServletException Indicates a servlet error occurred
UnavailableException Indicates a servlet is unavailable

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

HttpServletRequest Enables servlet to read data from an HttpRequest


HttpServletResponse Enables servlet to write data to an HttpResponse
HttpSession Allows session data to be read and written
HttpSessionBindingListener Informs an object that is bound to or unbound from a session
 Classes

Class Description

Cookie Allows state information to be stored on a client machine


HttpServlet Provide methods to handle HttpRequests and responses
HttpSessionEvent Encapsulates a session changed event
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session value or
that a session attribute changed

Dept.of ISE, KIT, Tiptur Naveen N Page 23

You might also like