A Simple Servlet
To become familiar with the key servlet concepts, begin by building and testing
a simple servlet. The basic steps are the following:
1. Create and compile the servlet source code.
2. Start Tomcat.
3. Start a web browser and request the servlet.
1. Create and Compile the Servlet Source Code,To begin, create a file named
HelloServlet.java that contains the following program:
package servletDemo;
import java.io.*;
import Jakarta. Servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
• First, note that it imports the jakarta.servlet package. This package contains the
classes and interfaces required to build servlets.
• Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet
class provides functionality that simplifies the creation of a servlet. For example, it provides
versions of init( ) and destroy( ), which may be used as is. You need supply only the service( )
method.
• Inside HelloServlet, the service( ) method (which is inherited from GenericServlet) is
overridden. This method handles requests from a client.
• the first argument is a ServletRequest object. This enables the servlet to read data that is
provided via the client request.
• The second argument is a ServletResponse object. This enables the servlet to formulate a
response for the client.
• The call to setContentType( ) establishes the MIME type of the HTTP response.
• In this program, the MIME type is text/html. This indicates that the browser should interpret
the content as HTML source code.
• Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to
the client as part of the HTTP response.
• Then println( ) is used to write some simple HTML source code as the HTTP response.
• Compile this source code and place the HelloServlet.class file in the proper
Tomcat directory.
• Also, add HelloServlet to the web.xml file.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
id="WebApp_ID" version="6.0">
<servlet>
<servlet-name>helloservlet</servlet-name>
<servlet-class>DemoProject.HelloServlet</servlet-class> <!--
Fully qualified name -->
</servlet>
<servlet-mapping>
<servlet-name>helloservlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
2. Start Tomcat Server. Tomcat must be running before you try
to execute a servlet.
3. Start a web browser and request the servlet. Start a Web
Browser and Request the Servlet Start a web browser and
enter the URL shown here:
http://localhost:8080/DemoProject/helloservlet
Key Points About <url-pattern>:
▪ It defines the URL that the user/browser will use to
access the servlet.
▪ You can choose any valid URL pattern like /hello,
/myServlet, /api/data, etc.
▪ It should start with a forward slash (/).
The Servlet API
• Two packages contain the classes and interfaces that are required to build
the servlets. These are Jakarta.Servlet and Jakarta.Servlet.http.
• They constitute the core of the Servlet API. these packages are not part
of the Java core packages. Therefore, they are not included with java SE
(Standard Edition).
• Instead, they are provided by Tomcat(servlet Implementation). They are
also provided by Java EE (Enterprise Edition).
• The Servlet API has been in a process of ongoing development and
enhancement. The current servlet specification is version 6.0.
The jakarta.servlet package
The jakarta.servlet package contains a number of interfaces and
classes that establish the framework in which servlets operate. The
following table summarizes several key interfaces that are provided in this
package. The most significant of these is Servlet. All servlets must
implement this interface or extend a class that implements the interface.
The ServletRequest and ServletResponse interfaces are also very important.
The following table summarizes the core classes that are provided in
the jakarta.servlet package:
The Servlet Interface
• All servlets must implement the Servlet interface. It declares the init( ),
service( ), and destroy( ) methods that are called by the server during the
life cycle of a servlet.
• The getServletConfig() method is called by the servlet to obtain
initialization parameters.
• A servlet developer overrides the getServletInfo( ) method to provide a
string with useful information (for example, the version number). This
method is also invoked by the server.
The ServletConfig Interface
The ServletConfig interface allows a servlet to obtain configuration data when it
is loaded. The methods declared by this interface are summarized here.
The ServletContext Interface
The ServletContext interface enables servlets to obtain information about
their environment.
The ServletRequest Interface
The ServletRequest interface enables a servlet to obtain information
about a client request.
The ServletResponse Interface
The ServletResponse interface enables a servlet to formulate a response for
a client.
The GenericServlet Class
• 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:
1. void log(String s)
2. 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 ServletInputStream Class
• The ServletInputStream class extends InputStream.
• It is implemented by the servlet container and provides an input
stream that a servlet developer can use to read the data from a
client request.
• In addition to the input methods inherited from InputStream, a
method is provided to read bytes from the stream.
int readLine(byte[ ] buffer, int offset, int size) throws IOException
Here, buffer is the array into which size bytes are placed starting at
offset. The method returns the actual number of bytes read or –1 if an
end-of-stream condition is encountered.
The ServletOutputStream Class
• The ServletOutputStream class extends OutputStream.
• It is implemented by the servlet container and provides an output
stream that a servlet developer can use to write data to a client
response.
• In addition to the output methods provided by OutputStream, it
also defines the print( ) and println( ) methods, which output
data to the stream.
The Servlet Exception Classes
• javax.servlet defines two exceptions.
1. ServletException, which indicates that a servlet problem has occurred.
2. UnavailableException, which extends ServletException. It indicates
that a servlet is unavailable
Reading Servlet Parameters
• The ServletRequest interface includes methods that allow you to
read the names and values of parameters that are included in a
client request.
• action parameter of the form tag specifies a URL. The URL
identifies the servlet to process the HTTP POST request
The source code for PostParametersServlet.java is shown in the following
listing.
• The service( ) method is overridden to process client requests.
• The getParameterNames( ) method returns an enumeration of the
parameter names.
• These are processed in a loop.
• the parameter name and value are output to the client. The parameter
value is obtained via the getParameter( ) method.
PostParameters.html
<!DOCTYPE html>
<html>
<head>
<title>Submit Employee Info</title>
</head>
<body>
<center>
<form name="Form1" method="post" action="http://localhost:8080/readparam/read">
<table>
<tr>
<td><b>Employee Name</b></td>
<td><input type="text" name="e" size="25" value=""></td>
</tr>
<tr>
<td><b>Phone</b></td>
<td><input type="text" name="p" size="25" value=""></td>
</tr>
</table>
<br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
id="WebApp_ID"
version="6.0">
<servlet>
<servlet-name>readingParameters</servlet-name>
<servlet-class>readparam.PostParametersServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>readingParameters</servlet-name>
<url-pattern>/read</url-pattern>
</servlet-mapping>
</web-app>
import java.io.*;
import java.util.*; PostParametersServlet.java
import javax.servlet.*;
public class PostParametersServlet
extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
Run the PostParameters.html file( right click and click Run as on server)
Output
The jakarta.servlet.http Package
when working with HTTP, you will normally use the interfaces and classes in
jakarta.servlet.http. its functionality makes it easy to build servlets that
work with HTTP requests and responses.
The most important of these is HttpServlet. Servlet developers typically extend this
class in order to process HTTP requests.
The HttpServletRequest Interface
The HttpServletRequest interface enables a servlet to obtain
information about a client request. Several of its methods are
shown in Table.
The HttpServletResponse Interface
The HttpServletResponse interface enables a servlet to formulate
an HTTP response to a client. Several constants are defined. These
correspond to the different status codes that can be assigned to an
HTTP response. For example, SC_OK indicates that the HTTP
request succeeded, and SC_NOT_FOUND indicates that the
requested resource is not available. Several methods of this
interface are summarized in the following Table.
The HttpSession Interface
The HttpSession interface enables a servlet to read and write the
state information that is associated with an HTTP session.
Several of its methods are summarized in Table .All of these
methods throw an IllegalStateException if the session has already
been invalidated.
The Cookie Class
• The Cookie class encapsulates a cookie. A cookie is stored on a client
and contains state information. Cookies are valuable for tracking
user activities.
• For example, 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.
• A servlet can write a cookie to a user’s machine via the addCookie( )
method of the HttpServletResponse interface. The data for that
cookie is then included in the header of the HTTP response that is
sent to the browser.
The names and values of cookies are stored on the user’s
machine. Some of the information that can be saved for each
cookie includes the following:
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie
• The expiration date determines when this cookie is deleted from
the user’s machine. If an expiration date is not explicitly assigned
to a cookie, it is deleted when the current browser session ends.
• The domain and path of the cookie determine when it is
included in the header of an HTTP request.
• If the user enters a URL whose domain and path match these
values, the cookie is then supplied to the web server. Otherwise,
it is not.
• There is one constructor for Cookie. It has the signature shown
here:
Cookie(String name, String value)
Here, the name and value of the cookie are supplied as arguments
to the constructor.
The methods of the Cookie class are summarized in Table.
DEMO
Using Cookies
let’s develop a servlet that illustrates how to use cookies. The
servlet is invoked when a form on a web page is submitted.
AddCookie.html
<!DOCTYPE html>
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/Cookie/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit button">
</form>
</body>
</html>
AddCookieServlet.java
package Cookie;
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
GetCookiesServlet.java
package Cookie;
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
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();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app Web.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
id="WebApp_ID"
version="6.0">
<!-- AddCookieServlet Mapping -->
<servlet>
<servlet-name>AddCookie</servlet-name>
<servlet-class>Cookie.AddCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddCookie</servlet-name>
<url-pattern>/AddCookieServlet</url-pattern>
</servlet-mapping>
<!-- GetCookiesServlet Mapping -->
<servlet>
<servlet-name>GetCookies</servlet-name>
<servlet-class>Cookie.GetCookiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetCookies</servlet-name>
<url-pattern>/GetCookiesServlet</url-pattern>
• Compile the servlets(both AddCookieServlet.java and
GetCookiesServlet.java)
• Next, update the web.xml file
• Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display AddCookie.html in a browser.
3. Enter a value for MyCookie.
4. Submit the web page.
After completing these steps, you will observe that a feedback
message is displayed by the browser.
• Next, request the following URL via the browser:
http://localhost:8080/Cookie/GetCookiesServlet
• Observe that the name and value of the cookie are displayed in the
browser.
• In this example, an expiration date is not explicitly assigned to the
cookie via the setMaxAge( ) method of Cookie.
• Therefore, the cookie expires when the browser session ends. You
can experiment by using setMaxAge( ) and observe that the cookie
is then saved on the client machine.
The HttpServlet Class
• The HttpServlet class extends GenericServlet.
• It is commonly used when developing servlets that receive and
process HTTP requests. The methods defined by the HttpServlet class
are summarized in Table.
Handling HTTP Requests and Responses
• The HttpServlet class provides specialized methods that handle the
various types of HTTP requests.
• A servlet developer typically overrides one of these methods.
These methods are doDelete( ), doGet( ), doHead( ), doOptions( ),
doPost( ), doPut( ), and doTrace( ).
However, the GET and POST requests are commonly used when
handling form input.
Handling HTTP GET Requests
• To develop a servlet that handles an HTTP GET request.
The servlet is invoked when a form on a web page is submitted.
The example contains two files. A web page is defined in
ColorGet.html, and a servlet is defined in ColorGetServlet.java. The
HTML source code for ColorGet.html is shown in the following
listing. It defines a form that contains a select element and a submit
button. Notice that the action parameter of the form tag specifies a
URL. The URL identifies a servlet to process the HTTP GET request.
ColorPost.html
<!DOCTYPE html>
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/GETandPOST/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
ColorGetServlet.java
package GETandPOST;
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
response.setContentType("text/html");
tells the browser what kind of content you're sending in the HTTP response. In this case,
you're telling it:
“The response is in HTML format.”
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" id="WebApp_ID"
version="6.0">
<servlet>
<servlet-name>GETandPOST</servlet-name>
<servlet-class>GETandPOST.ColorGetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GETandPOST</servlet-name>
<url-pattern>/ColorGetServlet</url-pattern>
</servlet-mapping>
</web-app>
• Compile the servlet.
• update the web.xml file,
• Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the web page in a browser.
3. Select a color.
4. Submit the web page.
• After completing these steps, the browser will display the response that is
dynamically generated by the servlet.
• One other point: Parameters for an HTTP GET request are included as part
of the URL that is sent to the web server. Assume that the user selects the
red option and submits the form.
The URL sent from the browser to the server is
http://localhost:8080/examples/servlets/servlet/ColorGetServlet?color=Red
The characters to the right of the question mark are known as the query string
Handling HTTP POST Requests
• To develop a servlet that handles an HTTP POST request.
• The servlet is invoked when a form on a web page is submitted.
• It is identical to ColorGet.html except that the method parameter for the
form tag explicitly specifies that the POST method should be used, and the
action parameter for the form tag specifies a different servlet
ColorPost.html
<!DOCTYPE html>
<html>
<body>
<center>
<form name="Form1" method="post"
action="http://localhost:8080/GETandPOST/ColorServlet">
<B>Choose Color:</B>
<!-- Create a drop-down list with three color options -->
<select name="color" size="1">
<option value="Red">Red color</option>
<option value="Green">Green color</option>
<option value="Blue">Blue color</option>
</select>
<br><br>
<input type=submit value="Submit button">
</form>
</body>
</html>
ColorPosttServlet.java
package GETandPOST;
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class ColorPosttServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String colorchoice = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(colorchoice);
pw.close();
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" id="WebApp_ID"
version="6.0">
<servlet>
<servlet-name>GETandPOST</servlet-name>
<servlet-class>GETandPOST.ColorPosttServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GETandPOST</servlet-name>
<url-pattern>/ColorPostServlet</url-pattern>
</servlet-mapping>
</web-app>
NOTE:
• Parameters for an HTTP POST request are not included as part
of the URL that is sent to the web server.
• In this example, the URL sent from the browser to the server is
http://localhost:8080/GETandPOST/ColorPostServlet.
• The parameter names and values are sent in the body of the
HTTP request.
Session Tracking
• HTTP is a stateless protocol. Each request is independent of the
previous one.
• However, in some applications, it is necessary to save state
information so that information can be collected from several
interactions between a browser and a server. Sessions provide such
a mechanism.
• A session can be created via the getSession() method of
HttpServletRequest. An HttpSession object is returned.
• This object can store a set of bindings that associate names with
objects. The setAttribute(), getAttribute(), getAttributeNames(),
and removeAttribute() methods of HttpSession manage these
bindings.
• Session state is shared by all servlets that are associated with a
client.
• The getSession() method gets the current session.
• A new session is created if one does not already exist.
• The getAttribute() method is called to obtain the object that is
bound to the name "date".
• That object is a Date object that encapsulates the date and time
when this page was last accessed. (Of course, there is no such
binding when the page is first accessed.)
• A Date object encapsulating the current date and time is then
created. The setAttribute( ) method is called to bind the name
"date" to this object.
package Session;
import java.io.*;
import java.util.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date lastAccessTime = (Date) hs.getAttribute("lastVisit");
if (lastAccessTime != null) {
pw.println("Last access: " + lastAccessTime + "<br>");
}
// Store current time with the key "lastVisit"
Date currentTime = new Date();
hs.setAttribute("lastVisit", currentTime);
pw.println("Current date: " + currentTime);
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" id="WebApp_ID" version="6.0">
<servlet>
<servlet-name>Session Tracking</servlet-name>
<servlet-class>Session.DateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Session Tracking</servlet-name>
<url-pattern>/track-session</url-pattern>
</servlet-mapping>
</web-app>
• When you first request this servlet, the browser displays one line
with the current date and time information.
• On subsequent invocations, two lines are displayed. The first line
shows the date and time when the servlet was last accessed. The
second line shows the current date and time.
JSP
• JSP is a server-side program that is similar in design and functionality to a java
servlet.
• A JSP is called by a client to provide a web service.
• A JSP processes the request by using logic built into the JSP or by calling
other web components using java servlet technology
• Once the request is processed, the JSP responds by sending the results to
the client.
• A JSP differs from a JAVA servlet in the way in which the JSP is written.
• Java servlet is written using the Java programming and responses are
encoded as an output String that is passed to the println() method.
• The output String object is formatted in HTML,XML, or whatever
formats are required by the client.
• JSP is written in HTML, XML, or in the client’s format that is
interspersed with scripting elements, directives and actions
comprised of java programming and JSP syntax.
JSP tags
• JSP program consists of a combination of HTML tags and JSP tags that define
actions that is to be executed before the output of the full program is sent to
the browser.
• A JSP tag begins with "<%" which is followed by Java code, and ends with
"%>".
Ex:
<%@ page import=" import java.sql.*"; %>
<%@ include file="keogh\books.html" %>
<%@ taglib uri="myTags.tld" %>
• Expression tags
An expression tag opens with <%= and is used for an expression
statement whose result replaces the expression tag when the JS
Pvirtual engine resolves ISP tags. An expression tags closes with %>.
• Scriptlet tags
A scriptlet tag opens with <% and contains commonly used Javacontrol
statements and loops. A scriptlet tag ends with %>.
Variables and Objects in JSP programs
•Java variables and objects can be declared using the same
coding techniques as in Java.
•Declaration statements must be within a JSP tag and appear
before the variable or object is used in the program.
•an example where an integer variable "age" is declared and
initialized to 29 within a JSP tag.
•The JSP tag begins with <%!, making the statement available to
other JSP tags.
• The variable "age" is used in an expression tag embedded within an
HTML paragraph tag <p>.
• JSP expression tags begin with <%=, followed by the expression.
• The JSP engine resolves the expression before sending the output to
the browser.
• The tag <%=age%> is replaced with the value 29 before the HTML
paragraph tag is sent to the browser.
Sample.jsp
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%! int age=29; %>
<P> Your age is: <%=age %> </P>
</body>
•</html>
You are able to place multiple statements withina JSP tag by extending
the close ISP tag to another line in the ISP program.
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%! int age=29;
float salary;
int empnumber;
%>
</body>
</html>
•Besides variables, you are also able to declare objects, arrays,
and Java collections within a JSP tag using techniques similar to
those used in a Java program.
•Ex. shows how to declare an object and an array., the JSP
program creates three String objects, the first two declarations
implicitly allocate memory, and the third declaration explicitly
allocates memory. In addition, this JSP program creates arrays
and a Vector.
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%@ page import="java.util.Vector" %>
<%! String Name;
String [ ] Telephone = {"201-555-1212", "201-555-4433"};
String Company = new String();
Vector Assignments = new Vector();
int[] Grade = {100,82,93};
%>
</body>
</html>
Methods
• Methods in JSP (JavaServer Pages) allow for defining reusable
blocks of code within a JSP program, similar to methods in Java
programs.
• However, in JSP, the method definition is placed within a JSP tag.
Once defined, a method can be called from within a JSP tag.
• The method call in JSP is identical to how it's called in Java.
• The JSP tag that calls the method must be a jsp Expression tag,
which begins with <%=.
• The JSP engine handles the call by replacing the JSP tag with the
results returned by the method, which is then passed to the
browser.
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
boolean curve(int grade) {
return (10 + grade) >= 60;
}
%>
<p>Your curved grade is: <%= curve(80) %></p>
</body>
</html>
How to define and use an overloaded
<html>method
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%! boolean curve (int grade)
{
return (10 + grade)>= 60;
}
boolean curve (int grade, int curveValue)
{
return (curveValue+ grade)>=60;
}
%>
<P> Your curved grade is: <%=curve (80, 10)%> </P>
<P> Your curved grade is: <%=curve (70)%> </P>
</body>
</html>
Control Statements(if and Switch statement)
<body>
<%! int grade = 70; %>
<% if (grade > 69) { %>
<p>You passed!</p>
<% } else { %>
<p>Better luck next time.</p>
<% } %>
<%
switch (grade) {
case 90:
out.println("<p>Your final grade is an A</p>");
break;
case 80:
out.println("<p>Your final grade is a B</p>");
break;
case 70:
out.println("<p>Your final grade is a C</p>");
break;
case 60:
out.println("<p>Your final grade is an F</p>");
break;
default:
out.println("<p>Grade not recognized.</p>");
}
%>
</body>
Loops
• 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 three kinds of loops commonly used in a JSP program. These are the
for loop, the while Joop, and the do... while loop.
• The for loop repeats, usually a specified number of times.
• The while loop executes continually as long as a 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.
• Loops play an important role in JSP database programs because
loops are used to populate HTML tables with data in the result set.
• Following sample program used to populate three HTML tables with
values assigned to an array.
•
<TD>Second</TD>
<TD>Third</TD>
</TR>
<TR>
<%
x = 0; // reset x before loop
while (x < 3) {
%>
<TD><%= Grade[x] %></TD>
<%
x++;
}
%>
</TR>
</TABLE>
<br>
<!-- Table using do-while loop -->
<TABLE border="1">
<TR>
<TD>First</TD>
<TD>Second</TD>
<TD>Third</TD>
</TR>
<TR>
<%
x = 0; // reset x before do-while
do {
%>
<TD><%= Grade[x] %></TD>
<%
x++;
output
Tomcat
• JSP programs are executed by a JSP Virtual Machine that runs on a
web server.
• Therefore, you'll need to have access to a JSP Virtual Machine to run
your JSP program.
• Alternatively, you can use an integrated development environment
such as JBuilder that has a built-in ISP Virtual Machine or you can
download and install a JSP Virtual Machine.
• One of the most popular JSP Virtual Machines is Tomcat, and it is
downloadable at no charge from the Apache web site. Apache is also
a popular web server that you can also download at no cost.
• You'll also need to have the Java Development Kit (JDK) installed on your
computer.
• You can download the IDK at o charge from the www.sun.com web site.
• Here's what you need to do to download and install Tomcat.
1.Connect to jakarta.apache.org.
2. Select Download.
3. Select Binaries to display the Binary Download page.
4.Create a folder from the root directory called tomcat.
5. Download the latest release of jakarta-tomcat.zip to the tomcat folder
6. Unzip jakarta-tomcat.zip. You can download a demo copy of WinZip from
www.winzip.com if you don't have a zip/unzip program installed on your
computer.
7. The extraction process should create the following folders in the
tomcat directory: bin, conf, doc, lib sre, and webapps.
8. Use a text editor such as Notepad and edit the JAVA_HOME variable
in the tomcat.bat file, which is located in the \tomcat\bin folder.. Make
sure the JAVA HOME variable is assigned the path where the JDK is
installed on your computer.
9. Open a DOS window and type \tomcat\bin\tomcat to start Tomcat.
10. Open your browser. Enter http://localhost:8080. The Tomcat home
page is displayed on the screen verifying that Tomcat is running.
Request String
• The brown generates a user request string whenever the Submit button is selected
The requent string consists of the URL and the query string.
• Here's a typical reques string:
http://www.jimkeogh.com/jsp/myprogram. Jsp? fname "Bob“ & lname =“Smith”
• Your program needs to parse the query string to extract values
of fields that are jo be processed by your program.
• You can parse the query string by using methods of the JSP
request object
•The getParameter(Name) is the method used to parse a
value of a specific field. The getParameter() method requires
an argument, which is the name of the field whose value you
want to retrieve.
•Let's say that you want to retrieve the value of the fname
field and the value of the Iname field in the previous request
string, Here are the statements that you'll need in your JSP
program:
<%! String Firstname = request.getParameter(fname);
String Lastname = request.getParameter(Iname);
%>
Cookies
• A cookie is a small piece of information created by a JSP program that
is stored on the client's hard disk by the browser.
• Cookies are used to store various kinds of information, such as user
preferences and an ID that tracks a session with a JSP database
system.
• You can create and read a cookie by using methods of the Cookie
class and the response object as illustrated in the following program
<%@ page import="jakarta.servlet.http.Cookie" %>
<%
// ===== Cookie Setting Section =====
String MyCookieName = "john";
String MyCookieValue = "JK1234";
Cookie newCookie = new Cookie(MyCookieName, MyCookieValue);
newCookie.setMaxAge(60 * 60); // Cookie expires in 1 hour
response.addCookie(newCookie);
%>
<html>
<head>
<title>JSP Programming</title>
</head>
<body>
<h2>Cookie Setting Section</h2>
<p>Cookie <b><%= MyCookieName %></b> is being set with value: <b><%= MyCookieValue
%></b></p>
<hr/>
<%
// ===== Cookie Reading Section =====
String CName = "";
String CValue = "";
boolean found = false;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
CName = cookies[i].getName();
CValue = cookies[i].getValue();
if (MyCookieName.equals(CName)) {
MyCookieValue = CValue;
found = true;
break;
}
}
}
%>
<h2>Cookie Reading Section</h2>
<% if (found) { %>
<p>Cookie Name: <%= MyCookieName %></p>
<p>Cookie Value: <%= MyCookieValue %></p>
<% } else { %>
<p>Cookie <b><%= MyCookieName %></b> not found (may
appear after a refresh).</p>
<% } %>
</body>
</html>
output
After refreshing the page
Session Objects
• A JSP database system is able to share information among JSP programs
within a session by using a session object. Each time a session is created,
a unique ID is assigned to the session and stored as a cookie.
• The unique ID enables JSP programs to track multiple sessions
simultaneously while maintaining data integrity of each session.
• The session ID is used to prevent the intermingling of information from
clients.
• In addition to the session ID, a session object is also used to store other
types of information, called attributes.
• An attribute can be login information, preferences, or even purchases
placed in an electronic shopping cart.
• Let's say that you built a Java database system that enables customers
to purchase goods online. There are several ways in which you can
share purchases.
• A better approach is to use a session object and store information
about purchases as session attributes. Session attributes can be
retrieved and modified each time the JSP program runs.
Session Objects program
<%@ page import="java.util.*" %>
<%
// Set a session attribute
String AtName = "Product";
String AtValue = "1234";
session.setAttribute(AtName, AtValue);
%>
<html>
<head>
<meta charset="UTF-8">
<title>Session Attributes</title>
</head>
<body>
<%
// Get all session attribute names and display them
Enumeration<String> purchases = session.getAttributeNames();
while (purchases.hasMoreElements()) {
String name = purchases.nextElement();
String value = (String) session.getAttribute(name);
%>
<p>Attribute Name: <%= name %></p>
<p>Attribute Value: <%= value %></p>
<%
}
%>
</body>
</html>