JSP - Architecture
JSP - Architecture
The web server needs a JSP engine ie. container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in
JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other services a JSP
needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and all
JSP elements are converted to Java code that implements the corresponding dynamic behavior
of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request
to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution, the servlet produces an output in HTML format, which the servlet engine passes to
the web server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally web browser handles the dynamically generated HTML page inside the HTTP response
exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the
modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the
JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the
JSP's contents. This makes the process more efficient than with other scripting languages (such as
PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet
JSP - Life Cycle
The key to understanding the low-level functionality of JSP is to understand the simple life cycle they
follow.
A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar
to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
Compilation
Initialization
Execution
Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:
JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the
page. If the page has never been compiled, or if the JSP has been modified since it was last compiled,
the JSP engine compiles the page.
The compilation process involves three steps:
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need
to perform JSP-specific initialization, override the jspInit() method:
Typically initialization is performed only once and as with the servlet init method, you generally initialize
database connections, open files, and create lookup tables in the jspInit method.
JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the
response for that request and this method is also responsible for generating responses to all seven of
the HTTP methods ie. GET, POST, DELETE etc.
JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy
when you need to perform any cleanup, such as releasing database connections or closing open files.
The Scriptlet:
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or
expressions that are valid in the page scripting language.
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple
and first example for JSP:
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
NOTE: Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment is
setup as per environment setup tutorial.
Let us keep above code in JSP file hello.jsp and put this file in C:\apache-tomcat-7.0.2\webapps\
ROOT directory and try to browse it by giving URL http://localhost:8080/hello.jsp. This would generate
following result:
JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code later in the JSP
file. You must declare the variable or method before you use it in the JSP file.
<jsp:declaration>
code fragment
</jsp:declaration>
JSP Expression:
A JSP expression element contains a scripting language expression that is evaluated, converted to a
String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression within a line of
text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java Language
Specification but you cannot use a semicolon to end an expression.
<jsp:expression>
expression
</jsp:expression>
<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful
when you want to hide or "comment out" part of your JSP page.
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
A Test of Comments
There are a small number of special constructs you can use in various cases to insert comments or
characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
Directive Description
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used
in the page
JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
Action elements are basically predefined functions and there are following JSP actions available:
Syntax Purpose
JSP supports nine automatically defined variables, which are also called implicit objects. These variables
are:
Objects Description
We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.
Control-Flow Statements:
JSP provides full power of Java to be embedded in your web application. You can use all the APIs and
building blocks of Java in your JSP programming including decision making statements, loops etc.
Decision-Making Statements:
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML
text included between Scriptlet tags.
Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside Scriptletas:
It's Wednesday.
Loop Statements:
You can also use three basic types of looping blocks in Java: for, while,and do…while blocks in your
JSP programming.
JSP Tutorial
JSP Tutorial
JSP Tutorial
JSP Tutorial
JSP Tutorial
JSP Tutorial
JSP Operators:
JSP supports all the logical and arithmetic operators supported by Java. Following table give a list of all
the operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom.
Within an expression, higher precedence operators will be evaluated first.
Integer: as in Java
String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped
as \\.
Null: null
JSP - Directives
JSP directives provide directions and instructions to the container, telling it how to handle certain
aspects of JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
Directives can have a number of attributes which you can list down as key-value pairs and
separated by commas.
The blanks between the @ symbol and the directive name, and between the last attribute and
the closing %>, are optional.
There are three types of directive tag:
Directive Description
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used
in the page
The page Directive:
The page directive is used to provide instructions to the container that pertain to the current JSP
page. You may code page directives anywhere in your JSP page. By convention, page directives
are coded at the top of the JSP page.
Following is the basic syntax of page directive:
<%@ page attribute="value" %>
Attributes:
Following is the list of attributes associated with page directive:
Attribute Purpose
Check more detail related to all the above attributes at Page Directive.
The include Directive:
The include directive is used to includes a file during the translation phase. This directive tells
the container to merge the content of other external files with the current JSP during the
translation phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="relative url" >
The filename in the include directive is actually a relative URL. If you just specify a filename with
no associated path, the JSP compiler assumes that the file is in the same directory as your JSP.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.include file="relative url" />
Where the uri attribute value resolves to a location the container understands and
the prefix attribute informs a container what bits of markup are custom actions.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
JSP - Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
Action elements are basically predefined functions and there are following JSP actions available:
Syntax Purpose
There are two attributes that are common to all Action elements: the id attribute and the scope attribute.
Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be
referenced inside the JSP page. If the Action creates an instance of an object the id value can
be used to reference it through the implicit object PageContext
Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and
the scope attribute are directly related, as the scope attribute determines the lifespan of the
object associated with the id. The scope attribute has four possible values: (a) page, (b)request,
(c)session, and (d) application.
This action lets you insert files into the page being generated. The syntax looks like this:
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet,
this action inserts the file at the time the page is requested.
Attribute Description
Example:
Let us define following two files (a)date.jsp and (b) main.jsp as follows:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page="date.jsp" flush="true" />
</center>
</body>
</html>
Now let us keep all these files in root directory and try to access main.jsp. This would display result
something like this:
The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope
variables. If an object is not found, it then tries to create the specified object.
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and
retrieve bean properties.
type Specifies the type of the variable that will refer to the
object.
Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid example
related to these actions.
The setProperty action sets the properties of a Bean. The Bean must have been previously defined
before this action. There are two basic ways to use the setProperty action:
You can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an
existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as
below:
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was
found.
Following is the list of attributes associated with setProperty action:
Attribute Description
The getProperty action is used to retrieve the value of a given property and converts it to a string, and
finally inserts it into the output.
The getProperty action has only two attributes, both of which are required ans simple syntax is as
follows:
Attribute Description
Example:
/* File: TestBean.java */
package action;
Compile above code to generated TestBean.class file and make sure that you copied TestBean.class in
C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and CLASSPATH variable should also
be set to this folder:
Now use the following code in main.jsp file which loads the bean and sets/gets a simple String
parameter:
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id="test" class="action.TestBean" />
<jsp:setProperty name="test"
property="message"
value="Hello JSP..." />
<p>Got message....</p>
</center>
</body>
</html>
Got message....
Hello JSP...
The forward action terminates the action of the current page and forwards the request to another
resource such as a static page, another JSP page, or a Java Servlet.
Attribute Description
Example:
Let us reuse following two files (a) date.jsp and (b) main.jsp as follows:
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:forward page="date.jsp" />
</center>
</body>
</html>
Now let us keep all these files in root directory and try to access main.jsp. This would display result
something like as below. Here it discarded content from main page and displayed content from
forwarded page only.
The plugin action is used to insert Java components into a JSP page. It determines the type of browser
and inserts the <object> or <embed> tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java component. The
Java component can be either an Applet or a JavaBean.
The plugin action has several attributes that correspond to common HTML tags used to format Java
components. The <param> element can also be used to send parameters to the Applet or Bean.
<jsp:fallback>
Unable to initialize Java Plugin
</jsp:fallback>
</jsp:plugin>
You can try this action using some applet if you are interested. A new element, the <fallback> element,
can be used to specify an error string to be sent to the user in case the component fails.
The <jsp:element>, lt;jsp:attribute> and <jsp:body> actions are used to define XML elements
dynamically. The word dynamically is important, because it means that the XML elements can be
generated at request time rather than statically at compile time.
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page">
The <jsp:text> action can be used to write template text in JSP pages and documents. Following is the
simple syntax for this action:
<jsp:text>Template data</jsp:text>
The body of the template cannot contain other elements; it can only contain text and EL expressions
( Note: EL expressions are explained in subsequent chapter). Note that in XML files, you cannot use
expressions such as ${whatever > 0}, because the greater than signs are illegal. Instead, use the gt
form, such as ${whatever gt 0} or an alternative is to embed the value in a CDATA section.
<jsp:text><![CDATA[<br>]]></jsp:text>
If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use the
<jsp:text> element as follows:
<jsp:text><![CDATA[<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">]]>
</jsp:text>
<head><title>jsp:text action</title></head>
<body>
<books><book><jsp:text>
Welcome to JSP Programming
</jsp:text></book></books>
</body>
</html>
JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each
page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also
called pre-defined variables.
Object Description
page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
The request object provides methods to get HTTP header information including form data, cookies,
HTTP methods etc.
We would see complete set of methods associated with request object in coming chapter: JSP - Client
Request.
The response object also defines the interfaces that deal with creating new HTTP headers. Through this
object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
We would see complete set of methods associated with response object in coming chapter: JSP - Server
Response.
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content
in a response.
The initial JspWriter object is instantiated differently depending on whether the page is buffered or not.
Buffering can be easily turned off by using the buffered='false' attribute of the page directive.
The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However,
JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object,
JspWriter throws IOExceptions.
Following are the important methods which we would use to write boolean char, int, double, object,
String etc.
Method Description
out.println(dataType dt) Print a data type value then terminate the line
with new line character.
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way
that session objects behave under Java Servlets.
The session object is used to track client session between client requests. We would see complete
usage of session object in coming chapter: JSP - Session Tracking.
The application object is direct wrapper around the ServletContext object for the generated Servlet and
in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created when
the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy()
method.
By adding an attribute to application, you can ensure that all JSP files that make up your web application
have access to it.
You can check a simple use of Application Object in chapter: JSP - Hits Counter
The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the
ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters
such as the paths or file locations etc.
The following config method is the only one you might ever use, and its usage is trivial:
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-name> element defined in the
WEB-INF\web.xml file
This object is intended as a means to access information about the page while avoiding most of the
implementation details.
This object stores references to the request and response objects for each request. The application,
config, session, and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page, including
the buffering information, the errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,
SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more
than 40 methods, about half of which are inherited from the javax.servlet.jsp. JspContext class.
One of the important methods is removeAttribute, which accepts either one or two arguments. For
example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the
following code only removes it from the page scope:
pageContext.removeAttribute("attrName", PAGE_SCOPE);
You can check a very good usage of pageContext in coming chapter: JSP - File Uploading.
This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.
The page object is really a direct synonym for the this object.
The exception object is a wrapper containing the exception thrown from the previous page. It is typically
used to generate an appropriate response to the error condition.
When a browser requests for a web page, it sends lot of information to the web server which can not be
read directly because this information travel as a part of header of HTTP request. You can check HTTP
Protocol for more information on this.
Following is the important header information which comes from browser side and you would use very
frequently in web programming:
Header Description
Accept This header specifies the MIME types that the browser
or other clients can handle. Values
of image/png or image/jpeg are the two most common
possibilities.
Accept-Charset This header specifies the character sets the browser can
use to display the information. For example ISO-8859-1.
Host This header specifies the host and port as given in the
original URL.
If-Modified-Since This header indicates that the client wants the page only
if it has been changed after the specified date. The
server sends a code, 304 which means Not
Modified header if no newer result is available.
The request object provides methods to get HTTP header information including form data, cookies,
HTTP methods etc.
There are following important methods which can be used to read HTTP header in your JSP program.
These method are available with HttpServletRequest object which represents client request to
webserver.
1
Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with
this request.
2
Enumeration getAttributeNames()
3
Enumeration getHeaderNames()
4
Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the
parameters contained in this request.
5
HttpSession getSession()
6
HttpSession getSession(boolean create)
7
Locale getLocale()
Returns the preferred Locale that the client will accept content in, based
on the Accept-Language header
8
Object getAttribute(String name)
9
ServletInputStream getInputStream()
10
String getAuthType()
Returns the name of the character encoding used in the body of this
request.
12
String getContentType()
Returns the MIME type of the body of the request, or null if the type is
not known.
13
String getContextPath()
Returns the portion of the request URI that indicates the context of the
request.
14
String getHeader(String name)
15
String getMethod()
Returns the name of the HTTP method with which this request was
made, for example, GET, POST, or PUT.
16
String getParameter(String name)
17
String getPathInfo()
Returns any extra path information associated with the URL the client
sent when it made this request.
18
String getProtocol()
19
String getQueryString()
Returns the query string that is contained in the request URL after the
path.
20
String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the
request.
21
String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
22
String getRemoteUser()
Returns the login of the user making this request, if the user has been
authenticated, or null if the user has not been authenticated.
23
String getRequestURI()
Returns the part of this request's URL from the protocol name up to the
query string in the first line of the HTTP request.
24
String getRequestedSessionId()
25
String getServletPath()
Returns the part of this request's URL that calls the JSP.
26
String[] getParameterValues(String name)
Returns an array of String objects containing all of the values the given
request parameter has, or null if the parameter does not exist.
27
boolean isSecure()
28
int getContentLength()
Returns the length, in bytes, of the request body and made available by
the input stream, or -1 if the length is not known.
29
int getIntHeader(String name)
30
int getServerPort()
Following is the example which uses getHeaderNames() method of HttpServletRequest to read the
HTTP header infromation. This method returns an Enumeration that contains the header information
associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement() method to get
each parameter name.
Now put the above code in main.jsp and try to access it. This would produce result something as follows:
accept */*
accept-language en-us
host localhost:8080
connection Keep-Alive
cache-control no-cache
To become more comfortable with other methods you can try few more above listed methods in the
same fashion.
When a Web server responds to a HTTP request to the browser, the response typically consists of a
status line, some response headers, a blank line, and the document. A typical response looks like this:
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the
example), and a very short message corresponding to the status code (OK in the example).
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser
from web server side and you would use them very frequently in web programming:
Header Description
Content-Disposition This header lets you request that the browser ask the
user to save the response to disk in a file of the given
name.
Content-Encoding This header specifies the way in which the page was
encoded during transmission.
Refresh This header specifies how soon the browser should ask
for an updated page. You can specify time in number of
seconds after which a page would be refreshed.
The response object also defines the interfaces that deal with creating new HTTP headers. Through this
object the JSP programmer can add new cookies or date stamps, HTTP status codes etc.
There are following methods which can be used to set HTTP response header in your servlet program.
These method are available with HttpServletResponse object which represents server response.
1
String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if
encoding is not needed, returns the URL unchanged.
2
String encodeURL(String url)
4
boolean isCommitted()
5
void addCookie(Cookie cookie)
6
void addDateHeader(String name, long date)
7
void addHeader(String name, String value)
8
void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.
9
void flushBuffer()
10
void reset()
Clears any data that exists in the buffer as well as the status code and
headers.
11
void resetBuffer()
12
void sendError(int sc)
Sends an error response to the client using the specified status code
and clearing the buffer.
13
void sendError(int sc, String msg)
14
void sendRedirect(String location)
15
void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.
16
void setCharacterEncoding(String charset)
Sets the character encoding (MIME charset) of the response being sent
to the client, for example, to UTF-8.
17
void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets,
this method sets the HTTP Content-Length header.
18
void setContentType(String type)
Sets the content type of the response being sent to the client, if the
response has not been committed yet.
19
void setDateHeader(String name, long date)
20
void setHeader(String name, String value)
21
void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.
22
void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed
yet.
23
void setStatus(int sc)
Following example would use setIntHeader() method to set Refresh header to simulate a digital clock:
Now put the above code in main.jsp and try to access it. This would display current system time after
every 5 seconds as follows. Just run the JSP and wait to see the result:
To become more comfortable with other methods you can try few more above listed methods in the
same fashion.
An initial status line + CRLF ( Carriage Return + Line Feed ie. New Line )
Zero or more header lines + CRLF
A blank line ie. a CRLF
An optional message body like file, query data or query output.
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the
example), and a very short message corresponding to the status code (OK in the example).
Following is a list of HTTP status codes and associated messages that might be returned from the Web
Server:
203 Non-authoritative
Information
204 No Content
300 A link list. The user can select a link and go to that
Multiple Choices
location. Maximum five addresses
400 Bad Request The server did not understand the request
402 Payment Required You can not use this code yet
404 Not Found The server can not find the requested page.
405 Method Not The method specified in the request is not allowed.
Allowed
407 Proxy You must authenticate with a proxy server before this
Authentication request can be served.
Required
408 The request took longer than the server was prepared
Request Timeout
to wait.
413 Request Entity The server will not accept the request, because the
Too Large request entity is too large.
414 The server will not accept the request, because the
Request-url Too url is too long. Occurs when you convert a "post"
Long request to a "get" request with a long query
information.
415 Unsupported The server will not accept the request, because the
Media Type media type is not supported.
500 Internal Server The request was not completed. The server met an
Error unexpected condition
501 The request was not completed. The server did not
Not Implemented
support the functionality required.
505 HTTP Version Not The server does not support the "http protocol"
Supported version.
There are following methods which can be used to set HTTP Status Code in your servlet program.
These method are available with HttpServletResponse object.
1
public void setStatus ( int statusCode )
This method sets an arbitrary status code. The setStatus method takes
an int (the status code) as an argument. If your response includes a
special status code and a document, be sure to call setStatus before
actually returning any of the content with the PrintWriter.
2
public void sendRedirect(String url)
3
public void sendError(int code, String message)
This method sends a status code (usually 404) along with a short
message that is automatically formatted inside an HTML document and
sent to the client.
Following is the example which would send 407 error code to the client browser and browser would
show you "Need authentication!!!" message.
<html>
<head>
<title>Setting HTTP Status Code</title>
</head>
<body>
<%
// Set error code and reason.
response.sendError(407, "Need authentication!!!" );
%>
</body>
</html>
description The client must first authenticate itself with the proxy (Need authentication!!!).
Apache Tomcat/5.5.29
To become more comfortable with HTTP status codes, try to set different status codes and their
description.
Advertisements
Previous Page
Next Page
You must have come across many situations when you need to pass some information from your
browser to web server and ultimately to your backend program. The browser uses two methods to pass
this information to web server. These methods are GET Method and POST Method.
GET method:
The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? character as follows:
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web server and it produces a
long string that appears in your browser's Location:box. Never use the GET method if you have
password or other sensitive information to pass to the server.
The GET method has size limitation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable which can be handled using getQueryString() and
getParameter() methods of request object.
POST method:
A generally more reliable method of passing information to a backend program is the POST method.
This method packages the information in exactly the same way as GET methods, but instead of sending
it as a text string after a ? in the URL it sends it as a separate message. This message comes to the
backend program in the form of the standard input which you can parse and use for your processing.
JSP handles this type of requests using getParameter() method to read simple parameters and
getInputStream() method to read binary data stream coming from the client.
JSP handles form data parsing automatically using the following methods depending on the situation:
getParameter(): You call request.getParameter() method to get the value of a form parameter.
getParameterValues(): Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.
getParameterNames(): Call this method if you want a complete list of all parameters in the
current request.
getInputStream(): Call this method to read binary data stream coming from the client.
Here is a simple URL which will pass two values to HelloForm program using GET method.
http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI
Below is main.jsp JSP program to handle input given by web browser. We are going to
use getParameter() method which makes it very easy to access passed information:
<html>
<head>
<title>Using GET Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Here is a simple example which passes two values using HTML FORM and submit button. We are going
to use same JSP main.jsp to handle this input.
<html>
<body>
<form action="main.jsp" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button to see the result on your local
machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned
in the above example.
Let us do little modification in the above JSP to handle GET as well as POST methods. Below
is main.jsp JSP program to handle input given by web browser using GET or POST methods.
Infact there is no change in above JSP because only way of passing parameters is changed and no
binary data is being passed to the JSP program. File handling related concepts would be explained in
separate chapter where we need to read binary data stream.
<html>
<head>
<title>Using GET and POST Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
<html>
<body>
<form action="main.jsp" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
First Name:
Last Name:
Try to enter First and Last Name and then click submit button to see the result on your local machine
where tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above examples.
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<html>
<body>
<form action="main.jsp" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" />
Chemistry
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
Maths Flag : : on
Chemistry Flag: : on
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement() method to get
each parameter name.
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
%>
</table>
</center>
</body>
</html>
<html>
<body>
<form action="main.jsp" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chem
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
Now try calling JSP using above Hello.htm, this would generate a result something like as below based
on the provided input:
maths on
chemistry on
You can try above JSP to read any other form's data which is having other objects like text box, radio
button or drop down box etc.
JSP - Filters
Advertisements
Previous Page
Next Page
Servlet and JSP Filters are Java classes that can be used in Servlet and JSP Programming for the
following purposes:
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
Authentication Filters.
Encryption Filters .
Tokenizing Filters .
XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet or JSP
names or URL patterns in your application's deployment descriptor. The deployment descriptor file
web.xml can be found in <Tomcat-installation-directory>\conf directory.
When the JSP container starts up your web application, it creates an instance of each filter that you have
declared in the deployment descriptor. The filters execute in the order that they are declared in the
deployment descriptor.
A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter
interface defines three methods:
1
public void doFilter (ServletRequest, ServletResponse, FilterChain)
2
public void init(FilterConfig filterConfig)
3
public void destroy()
Following is the JSP Filter Example that would print the clients IP address and current date time each
time it would access any JSP file. This example would give you basic understanding of JSP Filter, but
you can write more sophisticated filter applications using the same concept:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
Compile LogFilter.java in usual way and put your LogFilter.class class file in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/classes.
Filters are defined and then mapped to a URL or JSP file name, in much the same way as Servlet is
defined and then mapped to a URL pattern in web.xml file. Create the following entry for filter tag in the
deployment descriptor file web.xml
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The above filter would apply to all the servlets and JSP because we specified /* in our configuration. You
can specify a particular servlet or JSP path if you want to apply filter on few servlets or JSP only.
Now try to call any servlet or JSP in usual way and you would see generated log in you web server log.
You can use Log4J logger to log above log in a separate file.
Your web application may define several different filters with a specific purpose. Consider, you define
two filters AuthenFilter and LogFilter. Rest of the process would remain as explained above except you
need to create a different mapping as mentioned below:
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter>
<filter-name>AuthenFilter</filter-name>
<filter-class>AuthenFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The order of filter-mapping elements in web.xml determines the order in which the web container applies
the filter to the servlet or JSP. To reverse the order of the filter, you just need to reverse the filter-
mapping elements in the web.xml file.
For example, above example would apply LogFilter first and then it would apply AuthenFilter to any
servlet or JSP but the following example would reverse the order:
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Advertisements
Previous Page
Next Page
Cookies are text files stored on the client computer and they are kept for various information tracking
purpose. JSP transparently supports HTTP cookies using underlying servlet technology.
Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user or may be for some
other purpose as well.
This chapter will teach you how to set or reset cookies, how to access them and how to delete them
using JSP programs.
The Anatomy of a Cookie:
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a
browser). A JSP that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain.
The name and value will be URL encoded. The expires field is an instruction to the browser to "forget"
the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the
user points the browser at any page that matches the path and domain of the cookie, it will resend the
cookie to the server. The browser's headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A JSP script will then have access to the cookies through the request
method request.getCookies() which returns an array of Cookie objects.
Following is the list of useful methods associated with Cookie object which you can use while
manipulating cookies in JSP:
S.N. Method & Description
1
public void setDomain(String pattern)
This method sets the domain to which cookie applies, for example
tutorialspoint.com.
2
public String getDomain()
This method gets the domain to which cookie applies, for example
tutorialspoint.com.
3
public void setMaxAge(int expiry)
This method sets how much time (in seconds) should elapse before the
cookie expires. If you don't set this, the cookie will last only for the
current session.
4
public int getMaxAge()
5
public String getName()
This method returns the name of the cookie. The name cannot be
changed after creation.
6
public void setValue(String newValue)
7
public String getValue()
This method gets the value associated with the cookie.
8
public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't
specify a path, the cookie is returned for all URLs in the same directory
as the current page as well as all subdirectories.
9
public String getPath()
10
public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should
only be sent over encrypted (i.e. SSL) connections.
11
public void setComment(String purpose)
12
public String getComment()
This method returns the comment describing the purpose of this cookie,
or null if the cookie has no comment.
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value,
both of which are strings.
[]()=,"/?@:;
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should
be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add
cookies in the HTTP response header as follows:
response.addCookie(cookie);
Example:
Let us modify our Form Example to set the cookies for first and last name.
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));
Let us put above code in main.jsp file and use it in the following HTML page:
<html>
<body>
<form action="main.jsp" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Keep above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installation-
directory>/webapps/ROOT directory. When you would access http://localhost:8080/hello.jsp, here is the
actual output of the above form.
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button. This would display first name and
last name on your screen and same time it would set two cookies firstName and lastName which would
be passed back to the server when next time you would press Submit button.
Next section would explain you how you would access these cookies back in your web application.
Example:
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}else{
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html>
Now let us put above code in main.jsp file and try to access it. If you would have set first_name cookie
as "John" and last_name cookie as "Player" then running http://localhost:8080/main.jsp would display
the following result:
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up
following three steps:
Set cookie age as zero using setMaxAge() method to delete an existing cookie.
Example:
Following example would delete and existing cookie named "first_name" and when you would run
main.jsp JSP next time it would return null value for first_name.
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ){
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " +
cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>
</html>
Now let us put above code in main.jsp file and try to access it. It would display the following result:
Cookies Name and Value
Now try to run http://localhost:8080/main.jsp once again and it should display only one cookie as follows:
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet
Options. To delete all cookies, press Delete Cookies.
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a
separate connection to the Web server and the server automatically does not keep any record of
previous client request.
Still there are following three ways to maintain session between web client and web server:
Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests
from the client they can be recognized using the received cookie.
This may not be an effective way because many time browser does not support a cookie, so I would not
recommend to use this procedure to maintain the sessions.
This entry means that, when the form is submitted, the specified name and value are automatically
included in the GET or POST data. Each time when web browser sends request back, then session_id
value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>)
hypertext link does not result in a form submission, so hidden form fields also cannot support general
session tracking.
URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and the server can
associate that session identifier with data it has stored about that session.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support
cookies but here drawback is that you would have generate every URL dynamically to assign a session
ID though page is simple static HTML page.
Apart from the above mentioned three ways, JSP makes use of servlet provided HttpSession Interface
which provides a way to identify a user across more than one page request or visit to a Web site and to
store information about that user.
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each
new client automatically. Disabling session tracking requires explicitly turning it off by setting the page
directive session attribute to false as follows:
The JSP engine exposes the HttpSession object to the JSP author through the implicit session object.
Since session object is already provided to the JSP programmer, the programmer can immediately
begin storing and retrieving data from the object without any initialization or getSession().
This example describes how to use the HttpSession object to find out the creation time and the last-
accessed time for a session. We would associate a new session with the request if one does not already
exist.
Now put above code in main.jsp and try to access http://localhost:8080/main.jsp. It would display the
following result when you would run for the first time:
Welcome to my website
Session Infomation
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 0
Now try to run the same JSP for second time, it would display following result.
Session Infomation
id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 1
When you are done with a user's session data, you have several options:
Remove a particular attribute: You can call public void removeAttribute(String name) method
to delete the value associated with a particular key.
Delete the whole session: You can call public void invalidate() method to discard an entire
session.
Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to
set the timeout for a session individually.
Log the user out: The servers that support servlets 2.4, you can call logout to log the client out
of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you
can configure session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds.
So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.
A JSP can be used with an HTML form tag to allow users to upload files to the server. An uploaded file
could be a text file or binary or image file or any document.
The form method attribute should be set to POST method and GET method can not be used.
The form action attribute should be set to a JSP file which would handle file uploading at
backend server. Following example is using uploadFile.jsp program file to upload file.
To upload a single file you should use a single <input .../> tag with attribute type="file". To allow
multiple files uploading, include more than one input tags with different values for the name
attribute. The browser associates a Browse button with each of them.
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This will display following result which would allow to select a file from local PC and when user would
click at "Upload File", form would be submitted along with the selected file:
File Upload:
Select a file to upload:
NOTE: Above form is just dummy form and would not work, you should try above code at your machine
to make it work.
First let us define a location where uploaded files would be stored. You can hard code this in your
program or this directory name could also be added using an external configuration such as a context-
param element in web.xml as follows:
<web-app>
....
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
c:\apache-tomcat-5.5.29\webapps\data\
</param-value>
</context-param>
....
</web-app>
Following is the source code for UploadFile.jsp which can handle multiple file uploading at a time. Before
proceeding you have make sure the followings:
Following example depends on FileUpload, so make sure you have the latest version
of commons-fileupload.x.x.jar file in your classpath. You can download it
from http://commons.apache.org/fileupload/.
FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-
x.x.jar file in your classpath. You can download it fromhttp://commons.apache.org/io/.
While testing following example, you should upload a file which has less size
than maxFileSize otherwise file would not be uploaded.
Make sure you have created directories c:\temp and c:\apache-tomcat-5.5.29\webapps\data well
in advance.
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
out.println("<html>");
out.println("<head>");
out.println("<title>JSP File upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath +
fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}else{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>
Now try to upload files using the HTML form which you created above. When you would try
http://localhost:8080/UploadFile.htm, it would display following result which would help you uploading
any file from your local machine.
File Upload: