15advanced JAVA For Beginners JSP, JSTL, JSON and SERVLET TUTORIALS... Etc (Learn With Examples)
15advanced JAVA For Beginners JSP, JSTL, JSON and SERVLET TUTORIALS... Etc (Learn With Examples)
For Beginners
Navi Feroz
About,
Java Server Pages (JSP) is a server side technology for developing dynamic
web pages. This is mainly used for implementing presentation layer (GUI
Part) of an application. A complete JSP code is more like a HTML with bits
of java code in it. JSP is an extension of servlets and every JSP page first
gets converted into servlets by JSP container before processing the client’s
request.
These tutorials are written for beginners, so even if you have no prior
knowledge in this, you won’t face any difficulty understanding these
tutorials.
Objectives of our book is to impact basic knowledge in “ADVANCED
JAVA” for all the program learners. All the programs are clearly explained
with some examples.
© Copyright disclaimer:
The e-book name of” ADVANCED JAVA” are prepared for the student
and employees for their developing and pictures are directly provide for
understanding purpose under the copyright act.
Content:
JSP OVERVIEW
1. Introduction to Java Server Pages
2. Java Server Pages (JSP) Life Cycle
SCRIPTLETS
3. JSP Scriptlets
ACTION TAGS
4. Introduction Action tags
5. Include action tag
6. Include action with parameter
7. Forward action tag
8. jsp:useBean, jsp:setProperty and jsp:getProperty action tag
EXPRESSIONS
9. Expression Tag
DECLARATIONS
10. Declarations tag
JSP IMPLICIT OBJECTS
11. JSP Implicit Objects
12. OUT Implicit Object
13. Request Implicit Object
14. Response Implicit Object
15. Session Implicit Object
16. Application Implicit Object
17. Exception Implicit Object
18. PageContext Implicit Object
19. Config implicit object
EXPRESSION LANGUAGE (EL) IN JSP
20. Expression language (EL)
EXCEPTION HANDLING
21. Exception handling in JSP
CUSTOM TAGS
22. Custom tags in JSP
23. How to access the body of custom tags
DIRECTIVES
24. Page and Taglib directive
25. Include Directive
26. Include action with parameters
JSTL
27. JSTL Core Tags
28. JSTL Functions
JSON TUTORIALS
29. JSON Tutorials
SERVLET TUTORIALS
30. Servlet Introduction
31. Servlet API
32. Servlet Interface
33. GenericServlet Class
34. HttpServlet class
35. How to create and run Servlet in Eclipse IDE
36. Servlet Life Cycle
37. Working of Servlet
38. Welcome-file-list tag in web.xml file of Project
39. Use load-on-startup tag in web.xml file
40. ServletRequest Interface
41. RequestDispatcher methods
42. ServletConfig Interface
43. ServletContext Interface
JSP OVERVIEW
Note:
The hyperlink is given below at the some of the topics to go back
to their linked headings because some topics are linked to each
other to get better scope of reading to their related topics.so don’t
get confused during reading.
Introduction to Java Server Pages
JSP is a server side technology that does all the processing at server. It is
used for creating dynamic web applications, using java as programming
language.
Basically, any html file can be converted to JSP file by just changing the
file extension from “.html” to “.jsp”, it would run just fine. What
differentiates JSP from HTML is the ability to use java code inside HTML.
In JSP, you can embed Java code in HTML using JSP tags. E.g. run the
code below, every time you run this, it would display the current time. That
is what makes this code dynamic.
<HTML>
<BODY>
Hello JavaBook Readers!
Current time is: <%= new java.util.Date() %>
</BODY>
</HTML>
In the above example there are many type of JSP elements present such as
Expression, JSP comment, Declaration element etc. We will see each one of
them in upcoming JSP tutorials but as of now you can only focus on
Scriptlets. The below are the scriptlets statements used in above example –
[code language=”java”]
<%if(localstring.equals("JSP scriptlet"))
out.println("Hi"+string2);
else
out.println("hello");
%>[/code]
The above code is a JSP scriptlet (notice starting <% and ending %> tags).
If you analyze above piece of code then you would find that the code inside
tags is a pure java code so in order to execute java code in JSP we use
scriptlets.
[code language=”java”]<%String string1 ="JSP scriptlet";%>[/code]
NOTE:
GO BACK FROM HERE
Declarations
ACTION TAGS
JSP Actions – Java Server Pages
Directives vs Actions
1. Directives are used during translation phase while actions are used
during request processing phase.
2. Unlike Directives Actions are re-evaluated each time the page is
accessed.
3. The following are the action elements used in JSP:
1. <jsp:include> Action
Like include page directive this action is also used to insert a JSP file in
another file.
<jsp:include> vs include directive:
It has the same difference which I mentioned at the beginning of the article
(directive vs action). In <jsp:include> the file is being included during
request processing while in case of include directive it has been included at
translation phase.
Syntax:
<jsp:include page="page URL" flush="Boolean Value" />
Here page URL is: the location of the page needs to be included & flush
value can be either true or false (Boolean value).
Example:
<html>
<head>
<title>Demo of JSP include Action Tag</title>
</head>
<body>
<h3>JSP page: Demo Include</h3>
<jsp:include page="sample.jsp" flush="false" />
</body>
</html>
Page: Page value is sample.jsp which means this is the page needs to be
included in the current file. Just the file name mentioned which shows that
the sample.jsp is in the same directory.
Flush: Its value is false, which means resource buffer has not been flushed
out before including to the current page.
JSP include action tag
JSP include action tag – JSP Tutorial
Include action tag is used for including another resource to the current JSP
page. The included resource can be a static page in HTML, JSP page or
Servlet. We can also pass parameters and their values to the resource which
we are including. Below I have shared two examples of <jsp:include>, one
which includes a page without passing any parameters and in second
example we are passing few parameters to the page which is being
included.
Syntax:
1) Include along with parameters.
<jsp:include page="Relative_URL_Of_Page">
<jsp:param ... />
<jsp:param ... />
<jsp:param ... />
...
<jsp:param ... />
</jsp:include>
Page2.jsp
<b>Page2.jsp</b><br>
<i> This is the content of Page2.jsp page</i>
Output:
Content of Page2.jsp has been appended in the index.jsp.
display.jsp
<html>
<head>
<title>Display Page</title>
</head>
<body>
<h2>Hello this is a display.jsp Page</h2>
UserID: <%=request.getParameter("userid") %><br>
Password is: <%=request.getParameter("password") %><br>
User Name: <%=request.getParameter("name") %><br>
Age: <%=request.getParameter("age") %>
</body>
</html>
Output:
As you can see that the content of display.jsp has been included in
index.jsp. Also, the parameters we have passed are displaying correctly in
the included page.
JSP include action with parameter example
JSP include action with parameter example
In order to pass the parameters we need to use the <jsp:param> action tag.
Example
In this example we are including a JSP page (file.jsp) to the main JSP page
(index.jsp) using <jsp:include> action tag. To pass the parameters from
index to file page we are using <jsp:param> action tag. We are passing
three parameters firstname, middlename and lastname, for each of these
parameters we need to specify the corresponding parameter name and
parameter value. The same we can extract at the included page using
expression language or expression tag & implicit object.
index.jsp
<html>
<head>
<title>JSP include with parameters example</title>
</head>
<body>
<jsp:include page="file.jsp" >
<jsp:param name="firstname" value="Chandru" />
<jsp:param name="middlename" value="Pratap" />
<jsp:param name="lastname" value="Prasad" />
</jsp:include>
</body>
</html>
file.jsp
${param.firstname}<br>
${param.middlename}<br>
${param.lastname}
Output:
As you can see that the included page displayed the parameters values
passed from the main page. For displaying the parameters on the file.jsp
page, we have used the expression language (${}). However you can also
use the following code which is using the JSP expression tag and request
implicit object.
<%= request.getParameter("firstname")%>
<%= request.getParameter("middlename")%>
<%= request.getParameter("lastname")%>
2. <jsp:forward> Action
<jsp:forward> is used for redirecting the request. When this action is
encountered on a JSP page the control gets transferred to the page
mentioned in this action.
Syntax:
<jsp:forward page="URL of the another static, JSP OR Servlet page" />
Example:
first.jsp
<html>
<head>
<title>Demo of JSP Forward Action Tag</title>
</head>
<body>
<h3>JSP page: Demo forward</h3>
<jsp:forward page="second.jsp" />
</body>
</html>
Now when JSP engine would execute first.jsp (the above code) then after
action tag, the request would be transferred to another JSP page
(second.jsp).
Note: first.jsp and second.jsp should be in the same directory otherwise
you have to specify the complete path of second.jsp.
JSP forward action tag
JSP forward action tag – JSP Tutorial
JSP forward action tag is used for forwarding a request to another resource
(It can be a JSP, static page such as html or Servlet). Request can be
forwarded with or without parameter. In this tutorial we will see examples
of <jsp:forward> action tag.
Syntax:
1) Forwarding along with parameters.
<jsp:forward page="display.jsp">
<jsp:param ... />
<jsp:param ... />
<jsp:param ... />
...
<jsp:param ... />
</jsp:forward>
index.jsp
<html>
<head>
<title>JSP forward action tag example</title>
</head>
<body>
<p align="center">My main JSP page</p>
<jsp:forward page="display.jsp" />
</body>
</html>
display.jsp
<html>
<head>
<title>Display Page</title>
</head>
<body>
Hello this is a display.jsp Page
</body>
</html>
Output:
Below is the output of above code. It is basically the content of display.jsp,
which clearly shows that index.jsp didn’t display as it forwarded the request
to the display.jsp page.
JSP Forward Example 2 – with parameters
Here we are passing the parameters along with forward request. For passing
parameters we are using <jsp:param> action tag. In this example we are
passing 4 parameters along with forward and later we are displaying them
on the forwarded page. In order to fetch the parameters on display.jsp page
we are using getParameter method of request implicit object.
index.jsp
<html>
<head>
<title>JSP forward example with parameters</title>
</head>
<body>
<jsp:forward page="display.jsp">
<jsp:param name="name" value="Chandru" />
<jsp:param name="site" value="JavaBook.com" />
<jsp:param name="tutorialname" value="jsp forward action" />
<jsp:param name="reqcamefrom" value="index.jsp" />
</jsp:forward>
</body>
</html>
display.jsp
<html>
<head>
<title>Display Page</title>
</head>
<body>
<h2>Hello this is a display.jsp Page</h2>
My name is: <%=request.getParameter("name") %><br>
Website: <%=request.getParameter("site") %><br>
Topic: <%=request.getParameter("tutorialname") %><br>
Forward Request came from the page:
<%=request.getParameter("reqcamefrom") %>
</body>
</html>
Output:
Above code directly displayed display.jsp page, which is displaying the
parameters passed from index.jsp page.
3. <jsp:param> Action
This action is useful for passing the parameters to Other JSP action tags
such as JSP include & JSP forward tag. This way new JSP pages can have
access to those parameters using request object itself.
Syntax:
<jsp: param name="param_name_here" value="value_of_parameter_here"
/>
In the above example first.jsp is passing three parameters (data, time &
data) to second.jsp and second.jsp can access these parameters using the
below code –
Date:<%= request.getParameter("date") %>
Time:<%= request.getParameter("time") %>
My Data:<%= request.getParameter("data") %>
4. <jsp:useBean> Action
This action is useful when you want to use Beans in a JSP page, through
this tag you can easily invoke a bean.
Syntax:
<jsp: useBean id="unique_name_to_identify_bean"
class="package_name.class_name" />
Syntax of jsp:setProperty:
<jsp:setProperty name="unique_name_to_identify_bean"
property="property_name" />
Syntax of jsp:getProperty:
<jsp:getProperty name="unique_name_to_identify_bean"
property="property_name" />
index.jsp
<html>
<head><title>
useBean, getProperty and setProperty example
</title></head>
<form action="userdetails.jsp" method="post">
User Name: <input type="text" name="username"><br>
User Password: <input type="password" name="password"><br>
User Age: <input type="text" name="age"><br>
<input type="submit" value="register">
</form>
</html>
userdetails.jsp
<jsp:useBean id="userinfo" class="javabook.com.Details"></jsp:useBean>
<jsp:setProperty property="*" name="userinfo"/>
You have enterted below details:<br>
<jsp:getProperty property="username" name="userinfo"/><br>
<jsp:getProperty property="password" name="userinfo"/><br>
<jsp:getProperty property="age" name="userinfo" /><br>
Output:
Note:
Go back from here:
Expression language (EL) in JSP
EXPRESSION
Expressions Tag
Expression tag – Mainly used for display the content on the browser by
sending back the result to the client through response object.
JSP Expression Tag – JSP Tutorial
Expression Tag evaluate the expression placed in it, converts the result into
String and send the result back to the client through response object.
Basically it writes the result to the client (browser).
Syntax:
<%= expression %>
<html>
<head>
<title>JSP expression tag example1</title>
</head>
<body>
<%= 2+4*5 %>
</body>
</html>
Output:
Example 2: Expression of variables
In this example we have initialized few variables and passed the expression
of variables in the expression tag for result evaluation.
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>
<%
int a=10;
int b=20;
int c=30;
%>
<%= a+b+c %>
</body>
</html>
Output:
<html>
<head>
<title> JSP expression tag example3 </title>
</head>
<body>
<% application.setAttribute("MyName", "Chandru"); %>
<a href="display.jsp">Click here for display</a>
</body>
</html>
display.jsp
<html>
<head>
<title>Display Page</title>
</head>
<body>
<%="This is a String" %><br>
<%= application.getAttribute("MyName") %>
</body>
</html>
Output:
NOTE:
GO BACK FROM HERE:
JSP include action with parameter example
Declarations
DECLARATIONS
Declarations
Declaration tag – Learn how to declare variables and methods in JSP.
JSP Declaration tag – JSP Tutorial
Declaration tag is a block of java code for declaring class wide variables,
methods and classes. Whatever placed inside these tags gets initialized
during JSP initialization phase and has class scope. JSP container keeps this
code outside of the service method (_jspService()) to make them class level
variables and methods.
As we know that variables can be initialized using scriptlet too but those
declaration being placed inside _jspService() method which doesn’t make
them class wide declarations. On the other side, declaration tag can be used
for defining class level variables, methods and classes.
Syntax:
<%! Declaration %>
Note:
Get back from here
Expression language (EL) in JSP
OUT Implicit Object
OUT Implicit Object in JSP with examples
It’s an instance of javax.servlet.jsp.JspWriter. This allows us to access
Servlet output stream. The output which needs to be sent to the client
(browser) is passed through this object. In simple words out implicit object
is used to write content to the client.
Methods of OUT Implicit Object
1) void print()
2) void println()
3) void newLine()
4) void clear()
5) void clearBuffer()
6) void flush()
7) boolean isAutoFlush()
8) int getBufferSize()
9) int getRemaining()
Let us see each of the out’s method in detail –
1.Void print(): This method writes the value which has been passed to it.
For e.g. the below statement would display a sentence Out Implicit Object
in jSP – JavaBook to the output screen (client browser).
out.print(“Out Implicit Object in jSP - JavaBook”);
2.Void println(): This method is similar to the print() method, the only
difference between print and println is that the println() method adds a new
line character at the end. Let’s have a look at the difference with the help of
an example.
Print:
out.print(“hi”);
out.print(" ");
out.print(“hello”);
Output on browser: There will not be a new line between the outcomes
of all 3 out.print statements.
hi hello
println:
out.println(“hi”);
out.println(“hello”);
Output on browser:
hi
hello
3.Void newLine(): This method adds a new line to the output. Example –
out.print(“This will write content without a new line”);
out.newLine();
out.print(“I’m just an another print statement”);
Output:
This will write content without a new line
I’m just an another print statement
As you know print statement does not add a new line. We have added a new
line between two out.print statements using newLine() method.
4.Void clear(): It clears the output buffer without even letting it write the
buffer content to the client. This is how it can be called –
out.clear();
5.Void clearBuffer(): This method is similar to the clear() method. The
only difference between them is that when we invoke out.clear() on an
already flushed buffer it throws an exception, however out.clearBuffer()
doesn’t.
6.Void flush() : This method also clears the buffer just like clear()
method but it forces it to write the content to the output before flushing it,
which means whatever is there in buffer would be written to the client
screen before clearing the buffer.
7.Boolean is AutoFlush() : It returns a Boolean value true/false. It is
used to check whether the buffer is automatically flushed or not.
8.Int getBufferSize(): This method returns the size of output buffer in
bytes.
9.Int getRemaining(): It returns the number of bytes remaining before
hitting the buffer overflow condition.
OUT Implicit Object Example
In this example we are using print and println methods of OUT for
displaying few message to the client.
index.jsp
<HTML>
<HEAD>
<TITLE> OUT IMPLICIT OBJECT EXAMPLE </TITLE>
</HEAD>
<BODY>
<%
out.print( "print statement " );
out.println( "println" );
out.print("Another print statement");
%>
</BODY>
</HTML>
Output:
printstatement println
Another print statement
Request Implicit Object in JSP with examples
Methods of request Implicit Object
1. GetParameter(String name) – This method is used to get the value
of a request’s parameter. For example at login page user enters user-id and
password and once the credentials are verified the login page gets redirected
to user information page, then using request.getParameter we can get the
value of user-id and password which user has input at the login page.
String Uid= request.getParameter("user-id");
String Pass= request.getParameter("password");
index.html
<html>
<head>
<title>Enter UserName and Password</title>
</head>
<body>
<form action="userinfo.jsp">
Enter User Name: <input type="text" name="uname" /> <br><br>
Enter Password: <input type="text" name="pass" /> <br><br>
<input type="submit" value="Submit Details"/>
</form>
</body>
</html>
userinfo.jsp
<%@ page import = " java.util.* " %>
<html>
<body>
<%
String username=request.getParameter("uname");
String password=request.getParameter("pass");
out.print("Name: "+username+" Password: "+password);
%>
</body>
</html>
NOTE:
GO BACK FROM HERE:
JSP include action with parameter example
Response Implicit Object in JSP
Response Implicit Object in JSP with examples
Here we are going to discuss about response implicit object in JSP. It is an
instance of javax.servlet.http.HttpServletRequest and mainly used for
modifying the response which is being sent to the browser after processing
the client’s request.
Methods of response Implicit Object
1) void setContentType(String type)
2) void sendRedirect(String address)
3) void addHeader(String name, String value)
4) void setHeader(String name, String value)
5) boolean containsHeader(String name)
6) void addCookie(Cookie value)
7) void sendError(int status_code, String message)
8) boolean isCommitted()
9) void setStatus(int statuscode)
8.Boolean isCommitted() -It checks whether the Http Response has been
sent to the client, if yes then it returns true else it gives false.
<% if(response.isCommited())
{
<%--do something --%>
}else
{
<%--do something else --%>
} %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="checkdetails.jsp">
UserId: <input type="text" name="id" /> <br><br>
Password: <input type="text" name="pass" /> <br><br>
<input type="submit" value="Sign In!!"/>
</form>
</body>
</html>
This JSP page verifies the input id/pass against hard-coded values.
checkdetails.jsp
<html>
<head><title>Check Credentials</title>
</head>
<body>
<%
String uid=request.getParameter("id");
String password=request.getParameter("pass");
session.setAttribute("session-uid", uid);
if(uid.equals("Chandru") && password.equals("JavaBook"))
{
response.sendRedirect("success.jsp");
}
else
{
response.sendRedirect("failed.jsp");
}
%>
</body>
</html>
This JSP page would execute if id/pass are matched to the hardcoded
userid/password.
success.jsp
<html>
<head><title>Success Page</title>
</head>
<body>
<%
String data=(String)session.getAttribute("session-uid");
out.println("Welcome "+ data+"!!");
%>
</body>
</html>
The control will be redirected to this page if the credentials entered by user
are wrong.
failed.jsp
<html>
<head><title>Sign-in Failed Page</title>
</head>
<body>
<%
String data2=(String)session.getAttribute("session-uid");
out.println("Hi "+ data2+". Id/Password are wrong. Please try Again.");
%>
</body>
</html>
Output screenshot:
Login page
NOTE:
GET BACK HERE:
Expressions
Session Implicit Object
Session Implicit Object in JSP with examples
Session is most frequently used implicit object in JSP. The main usage of it
to gain access to all the user’s data till the user session is active.
The session.jsp page displays the name which user has entered in the index
page and it stores the the same variable in the session object so that it can
be fetched on any page until the session becomes inactive.
session.jsp
<html>
<head>
<title>Passing the input value to a session variable</title>
</head>
<body>
<%
String uname=request.getParameter("inputname");
out.print("Welcome "+ uname);
session.setAttribute("sessname",uname);
%>
<a href="output.jsp">Check Output Page Here </a>
</body>
</html>
In this page we are fetching the variable’s value from session object and
displaying it.
output.jsp
<html>
<head>
<title>Output page: Fetching the value from session</title>
</head>
<body>
<%
String name=(String)session.getAttribute("sessname");
out.print("Hello User: You have entered the name: "+name);
%>
</body>
</html>
Output Screens:
Application Implicit Object
Application Implicit Object in JSP with examples
Application implicit object is an instance of javax.servlet.ServletContext.
It is basically used for getting initialization parameters and for sharing the
attributes & their values across the entire JSP application, which means any
attribute set by application implicit object would be available to all the
JSP pages.
Methods:
Object getAttribute(String attributeName)
void setAttribute(String attributeName, Object object)
void removeAttribute(String objectName)
Enumeration getAttributeNames()
String getInitParameter(String paramname)
Enumeration getInitParameterNames()
String getRealPath(String value)
void log(String message)
URL getResource(String value)
InputStream getResourceAsStream(String path)
String getServerInfo()
String getMajorVersion()
String getMinorVersion()
1.Object getAttribute(String attributeName): It returns the object stored
in a given attribute name. For example the below statement would return
the object stored in attribute “MyAttr”.
String s = (String)application.getAttribute("MyAttr");
The above statement would have stored the attribute and its value. What
would be the value of ‘s’ if we use the below statement in any of the JSP
page?
String s= (String) application.getAttribute(“MyAttribute”);
String s value would be “This is the value of Attribute” since we have set it
using setAttribute method.
3.Void removeAttribute(String objectName): This method is used for
removing the given attribute from the application. For e.g. – It would
remove the Attribute “MyAttr” from the application. If we try to get the
value of a removed attribute using getAttribute method, it would return
Null.
application.removeAttribute(“MyAttr”);
4.Enumeration getAttributeNames(): This method returns the
enumeration of all the attribute names stored in the application implicit
object.
Enumeration e= application.getAttributeNames();
5.String getInitParameter(String paramname): It returns the value of
Initialization parameter for a given parameter name. Example –web.xml
<web-app>
…
<context-param>
<param-name>parameter1</param-name>
<param-value>ValueOfParameter1</param-value>
</context-param>
</web-app>
Suppose above is my web.xml file
String s=application.getInitParameter(“parameter1”);
The value of s will be “ValueOfParameter1”. Still confused where did it
come from? See the param-value tag in web.xml file.
6.Enumeration getInitParameterNames(): It returns the enumeration of
all the Initialization parameters.
Enumeration e= application.getinitParameterNames();
7.String getRealPath(String value): It converts a given path to an absolute
path in the file system.
String abspath = application.getRealPath(“/index.html”);
The value of abspath would be a complete http URL based on the existing
file system.
8.Void log(String message): This method writes the given message to the
JSP Engine’s (JSP container’s) default log file associated to the application.
application.log(“This is error 404 Page not found”);
The above call would write the message “This is error 404 Page not found”
to the default log file.
9.String getServerInfo(): This method returns the name and version of JSP
container (JSP Engine).
application.getServerInfo();
NOTE:
GET BACK FROM HERE:
Expressions
Exception Implicit Object
Exception Implicit Object in JSP with examples
In this tutorial, we will discuss exception implicit object of JSP. It is an
instance of java.lang. Throwable and the frequently used for exception
handling in JSP. This object is only available for error pages, which means a
JSP page should have isErrorPage to true in order to use exception implicit
object. Let’s understand this with the help of below example –
In the below JSP page we have set isErrorPage to true which is also an
attribute of Page directive, used for making a page eligible for exception
handling. Since this page is defined as a exception page in division.jsp, in
case of any exception condition this page will be invoked. Here we are
displaying the error message to the user using exception implicit object.
exception.jsp
<%@ page isErrorPage="true" %>
Got this Exception: <%= exception %>
Please correct the input data.
Output:
Screen with two input fields for two integer numbers.
NOTE:
GET BACK FROM HERE:
JSP Directives
PageContext Implicit Object
PageContext Implicit Object in JSP with examples
It is an instance of javax.servlet.jsp.PageContext. Using this object you
can find attribute, get attribute, set attribute and remove attribute at any of
the below levels –
1. JSP Page – Scope: PAGE_CONTEXT
2. HTTP Request – Scope: REQUEST_CONTEXT
3. HTTP Session – Scope: SESSION_CONTEXT
4. Application Level – Scope: APPLICATION_CONTEXT
Methods of pageContext Implicit Object
1. Object findAttribute (String AttributeName): This method searches
for the specified attribute in all four levels in the following order –
Page, Request, Session and Application. It returns NULL when no
attribute found at any of the level.
2. Object getAttribute (String AttributeName, int Scope): It looks for
an attribute in the specified scope. This method is similar to
findAttribute method; the only difference is that findAttribute looks in
all the four levels in a sequential order while getAttribute looks in a
specified scope. For e.g. – In the below statement the getAttribute
method would search for the attribute “JavaBook” in Session scope (or
Session level/layer). If it finds the attribute it would assign it to Object
obj else it would return Null.
Object obj = pageContext.getAttribute("JavaBook",
PageContext.SESSION_CONTEXT);
validation.jsp
In this page we are storing user’s credentials using pageContext implicit
object with the session scope, which means we will be able to access the
details till the user’s session is active. We can also store the attribute using
other scope parameters such as page, application and request.
<html>
<head> <title> Validation JSP Page</title>
</head>
<body>
<%
String id=request.getParameter("uid");
String pass=request.getParameter("upass");
out.println("hello "+id);
pageContext.setAttribute("UName", id, PageContext.SESSION_SCOPE);
pageContext.setAttribute("UPassword", pass,
PageContext.SESSION_SCOPE);
%>
<a href="display.jsp">Click here to see what you have entered </a>
</body>
</html>
display.jsp
In this JSP page we are fetching the stored attributes using getAttribute
method. The point to note here is that we have stored the attributes with
session scope so we must need to specify scope as session in order to fetch
those attribute’s value.
<html>
<head>
<title>Displaying User Details</title>
</head>
<body>
<%
String username= (String) pageContext.getAttribute("UName",
PageContext.SESSION_SCOPE);
String userpassword= (String) pageContext.getAttribute("UPassword",
PageContext.SESSION_SCOPE);
out.println("Hi "+username);
out.println("Your Password is: "+userpassword);
%>
</body>
</html>
Screenshots of the example’s output:
Login page where we are receiving User-Id and Password from user.
User Credentials display page which we have passed from login page to this
page through pageContext instance.
Config Implicit Object
Config Implicit Object in JSP with examples
It is an instance of javax.servlet.ServletConfig. Config Implicit object is
used for getting configuration information for a particular JSP page. Using
application implicit object we can get application-wide initialization
parameters, however using Config we can get initialization parameters of an
individual servlet mapping.
<servlet-mapping>
<servlet-name>JavaBookServlet</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
In this JSP page we are calling getServletName() method of config object
for fetching the servlet name from web.xml file.
<html>
<head> <title> Config Implicit Object</title>
</head>
<body>
<%
String sname=config.getServletName();
out.print("Servlet Name is: "+sname);
%>
</body>
</html>
Output:
This is the output screen for the above JSP page.
EXPRESSION LANGUAGE
Expression language (EL) in JSP
Expression language(EL) – We can easily access the data of variables,
bean components and expressions using Expression language. Must read
this tutorial for JSP Java.
Expression language (EL) has been introduced in JSP 2.0. The main
purpose of it to simplify the process of accessing data from bean properties
and from implicit objects. EL includes arithmetic, relational and logical
operators too.
Syntax of EL:
${expression}
Whatever present inside braces gets evaluated at runtime and being sent to
the output stream.
<html>
<head>
<title>Expression language example1</title>
</head>
<body>
${1<2}
${1+2+3}
</body>
</html>
Output:
Example 2: Value fetch using param variable of expression
language
In this example we are prompting user to enter name and roll number. On
the other JSP page we are fetching the entered details using param variable
of EL.
index.jsp
<html>
<head>
<title>Expression language example2</title>
</head>
<body>
<form action="display.jsp">
Student Name: <input type="text" name="stuname" /><br>
Student RollNum:<input type="text" name="rollno" /><br>
<input type="submit" value="Submit Details!!"/>
</form>
</body>
</html>
display.jsp
<html>
<head>
<title>Display Page</title>
</head>
<body>
Student name is ${ param.stuname } <br>
Student Roll No is ${ param.rollno }
</body>
</html>
Output:
Example 3: Getting values from application object.
In this example we have set the attributes using application implicit object
and on the display page we have got those attributes
using applicationScope of Expression language.
index.jsp
<html>
<head>
<title>EL example3</title>
</head>
<body>
<%
application.setAttribute("author", "Chandu");
application.setAttribute("Site", "JavaBook.com");
%>
<a href="display.jsp">Click</a>
</body>
</html>
display.jsp
<html>
<head>
<title>Display Page</title>
</head>
<body>
${applicationScope.author}<br>
${applicationScope.Site}
</body>
</html>
Output:
EL predefined variables:
Similar to implicit objects in JSP we have predefined variables in EL. In the
above examples we have used param and applicationScope, they are also
the part of these variables.
PageScope: It helps in getting the attribute stored in Page scope.
EL predefined variables:
Similar to implicit objects in JSP we have predefined variables in EL. In the
above examples we have used param and applicationScope, they are also
the part of these variables.
PageScope: It helps in getting the attribute stored in Page scope.
PageContext: Same as JSP PageContext object.
SessionScope: Fetches attributes from session scope, set by session object.
RequestScope: It used for getting the attributes from request scope. The
attribute which are set by the request implicit object.
Param: Similar to ServletRequest.getParameter. Refer Example 2.
ApplicationScope: Used for getting Applicaton level attributes. Same what
we see in Example 3.
Header: It helps in getting HTTP request headers as Strings.
HeaderValues: Used for fetching all the HTTP request headers.
InitParam: It links to context initialization parameters.
ParamValues: Same as ServletRequest.getParmeterValues.
Cookie: It maps to Cookie object.
Note:
GO BACK HERE:
JSP include action with parameter example
JSTL
EXCEPTION HANDLING
Exception handling
Exception handling in JSP – A complete tutorial to learn exception handling
in the JSP. We have shared two methods to handle exceptions.
Before going through exception handling in JSP, let us understand what is
exception and how it is different from errors.
Exception: These are nothing but the abnormal conditions which interrupts
the normal flow of execution. Mostly they occur because of the wrong data
entered by user. It is must to handle exceptions in order to give meaningful
message to the user so that user would be able to understand the issue and
take appropriate action.
Error: It can be an issue with the code or a system related issue. We should
not handle errors as they are meant to be fixed.
errorpage.jsp
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Display the Exception Message here</title>
</head>
<body>
<h2>errorpage.jsp</h2>
<i>An exception has occurred in the index.jsp Page.
Please fix the errors. Below is the error message:</i>
<b><%= exception %></b>
</body>
</html>
Output:
Exception handling using try catch blocks within scriptlets
We have handled the exception using try catch blocks in the below
example. Since try catch blocks are java code so it must be placed inside
sciptlet. In the below example I have declared that an array of length 5 and
tried to access the 7th element which does not exist. It caused Array Index
out of bounds exception.
error.jsp
<html>
<head>
<title>Exception handling using try catch blocks</title>
</head>
<body>
<%
try{
//I have defined an array of length 5
int arr[]={1,2,3,4,5};
//I'm assinging 7th element to int num
//which doesn't exist
int num=arr[6];
out.println("7th element of arr"+num);
}
catch (Exception exp){
out.println("There is something wrong: " + exp);
}
%>
</body>
</html>
Output of example 2:
CUSTOM TAGS
Custom Tags
Custom tags in JSP
How to access the body of custom tags
1) Tag handler class: In this class we specify what our custom tag will do
when it is used in a JSP page.
2) TLD file: Tag descriptor file where we will specify our tag name, tag
handler class and tag attributes.
3) JSP page: A JSP page where we will be using our custom tag.
Example:
In the below example we are creating a custom tag MyMsg which will
display the message “This is my own custom tag” when used in a JSP page.
TLD File
This file should present at the location: Project Name/WebContent/WEB-
INF/ and it should have a .tld extension.
Note:
<name> tag:custom tag name. In this example we have given it as MyMsg
<tag-class> tag: Fully qualified class name. Our tag handler
class Details.java is in package javabook.com so we have given the value
as javabook.com.Details.
message.tld
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>My Custom Tag</short-name>
<tag>
<name>MyMsg</name>
<tag-class>Javabook.com.Details</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Using custom tag in JSP:
Above we have created a custom tag named MyMsg. Here we will be using
it.
Note: taglib directive should have the TLD file path in uri field. Above we
have created the message.tld file so we have given the path of that file.
Choose any prefix and specify it in taglib directive’s prefix field. Here we
have specified it as myprefix.
Custom tag is called like this: <prefix:tagName/>. Our prefix
is myprefix and tag name is MyMsg so we have called it
as <myprefix:MyMsg/> in the below JSP page.
<%@ taglib prefix="myprefix" uri="WEB-INF/message.tld"%>
<html>
<head>
<title>Custom Tags in JSP Example</title>
</head>
<body>
<myprefix:MyMsg/>
</body>
</html>
Output:
This is my own custom tag
TLDfile: message.tld
Remember to have this file in WEB-INF folder.
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>My Custom Tag: MyMsg</short-name>
<tag>
<name>MyMsg</name>
<tag-class>javabook.com.Details</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>
JSP Page: index.jsp
<%@ taglib prefix="myprefix" uri="WEB-INF/message.tld"%>
<html>
<head>
<title>Accessing Custom Tag Body Example</title>
</head>
<body>
<myprefix:MyMsg>
Test String
</myprefix:MyMsg>
</body>
</html>
Output:
Test String Appended Custom Tag Message
JSP DIRECTIVES
JSP Directives
JSP Directives – Page and TagLib
Directives control the processing of an entire JSP page. It gives directions
to the server regarding processing of a page.
Syntax of Directives:
<%@ directive name [attribute name=“value” attribute name=“value”
........]%>
1) Page Directive
There are several attributes, which are used along with Page Directives and
these are –
1) import
2) session
3) isErrorPage
4) errorPage
5) ContentType
6) isThreadSafe
7) extends
8) info
9) language
10) autoflush
11) buffer
1. Import:
This attribute is used to import packages. While doing coding you may need
to include more than one packages, In such scenarios this page directive’s
attribute is very useful as it allows you to mention more than one packages
at the same place separated by commas (,). Alternatively you can have
multiple instances of page element each one with different package.
Syntax of import attribute –
<%@page import="value"%>
2. Session:
Generally while building a user interactive JSP application, we make sure
to give access to the user to get hold of his/her personal data till the session
is active. Consider an example of logging in into your bank account, we can
access all of your data till we signout (or session expires). In order to
maintain session for a page the session attribute should be true.
This attribute is to handle HTTP sessions for JSP pages. It can have two
values: true or false. Default value for session attribute is true, which means
if you do not mention this attribute, server may assume that HTTP session
is required for this page.
Default value for this attribute: true
Syntax:
<%@ page session="value"%>
The above code would allow a page to have session implicit objects.
<%@ page session="false"%>
If this code is specified in a JSP page, it means session objects will not be
available for that page. Hence session cannot be maintained for that page.
3. isErrorPage:
This attribute is used to specify whether the current JSP page can be used as
an error page for another JSP page. If value of isErrorPage is true it means
that the page can be used for exception handling for another page.
Generally this page has error/warning messages OR exception handling
codes and being called by another JSP page when there is an exception
occurred there.
There is another use of isErrorPage attribute – The exception implicit
object can only be available to those pages which has isErrorPage set to
true. If the value is false, the page cannot use exception implicit object.
Default value: false
Syntax:
<%@ page isErrorPage="value"%>
Here value is a JSP page name which has exception handling code (and
isErrorPage set to true).
Example of errorPage:
<%@ page errorPage="ExceptionHandling.jsp"%>
This means if any exception occurs on the JSP page where this code has
been placed, the ExceptionHandling.jsp (this page should have isErrorPage
true) page needs to be called.
5. ContentType:
This attribute is used to set the content type of a JSP page.
Default value: text/html
Syntax:
<%@ page contentType="value"%>
here value of content type can be anything such as: text/html, text/xml etc.
Example of contentType:
Below code can be used for text/html pages.
<%@ page contentType="text/html"%>
for text/xml based pages:
<%@ page contentType="text/xml"%>
6. isThreadSafe:
Let us understand this with an example. Suppose you have created a JSP
page and mentioned isThreadSafe as true, it means that the JSP page
supports multithreading (more than one thread can execute the JSP page
simultaneously). On the other hand if it is set to false then JSP engine won’t
allow multithreading which means only single thread will execute the page
code.
Default value for isThreadSafe attribute: true.
Syntax:
<%@ page isThreadSafe="value"%>
8. Extends:
Like java, here also this attribute is used to extend(inherit) the class.
Syntax:
<%@ page extends="value"%>
Value is package_name.class_name.
Example of extends:
The below code will inherit the SampleClass from package: mypackage
<%@ page extends="mypackage.SampleClass"%>
9. Info:
It provides a description to a JSP page. The string specified in info will
return when we will call getServletInfo() method.
Syntax:
<%@ page info="value"%>
10. language:
It specifies the scripting language( underlying language) being used in the
page.
Syntax of language:
<%@ page language="value"%>
Value is scripting language here.
Example of language attribute:
<%@ page language="java"%>
11. AutoFlush:
If it is true it means the buffer should be flushed whenever it is full. false
will throw an exception when buffer overflows.
Default value: True
Syntax of autoFlush:
<%@ page autoFlush="value"%>
12. isScriptingEnabled:
It has been dropped and not in use.
13. isELIgnored:
This attribute specify whether expressions will be evaluated or not.
Default value: true
Syntax of isELIgnored:
<%@ page isELIgnored="value"%>
value can be true or false.
Example of is ELIgnored attribute:
Any expression present inside JSP page will not be evaluated –
<%@ page isELIgnored="false"%>
Expression will be evaluated (true is a default value so no need to specify)-
<%@ page isELIgnored="true"%>
Include Directive
2) Include Directive
Include directive is used to copy the content of one JSP page to another. It’s
like including the code of one file into another.
Syntax:
<%@include file ="value"%>
Here value is the JSP file name which needs to be included. If the file is in
the same directory then just specify the file name otherwise complete URL
(or path) needs to be mentioned in the value field.
Note: It can be used anywhere in the page.
Example:
<%@include file="myJSP.jsp"%>
You can use the above code in your JSP page to copy the content of
myJSP.jsp file. However in this case both the JSP files must be in the same
directory. If the myJSP.jsp is in the different directory then instead of just
file name you would need to specify the complete path in above code.
Must Read:
Include Directive in detail in JSP
Include directive is used for merging external files to the current JSP page
during translation phase (The phase where JSP gets converted into the
equivalent Servlet).
Why we need to use the include directive? Can’t we simply add the
file’s content in the current JSP instead of using the directive?
We can copy the content of external file and paste it in the main
JSP,however it would not be a good practice. Let’s understand this with
the help of an example – I have 100 external files and 1 main JSP file. If I
just copy the content of all files in the main JSP then I have to edit it
whenever there is a change in any of the external file, instead we can
include all files using directive and edit the particular file whenever needed.
Also, by using include directive you can enhance the code re-usability –
Suppose there is a certain code or data which needs to be there in all the
JSP pages of your application then you can simply have that code/data in
one file and include the file in all the JSP pages.
The above two reasons can be considered as advantages of using include
directive.
Syntax:
This is the syntax of include directive in JSP.
<%@ include file="URL of the file" %>
file2.jsp
<p align="center">
This is File2.jsp
</p>
Output: The output would look like this when you run the above code. As
you can see we have included the content of file1 and file2 in out main JSP
page with the help of include directive.
3) Taglib Directive
This directive basically allows user to use Custom tags in JSP. we shall
discuss about Custom tags in detail in coming JSP tutorials. Taglib directive
helps you to declare custom tags in JSP page.
Syntax:
<%@taglib uri ="taglibURI" prefix="tag prefix"%>
As you can see that uri is having the location of custom tag library and
prefix is identifying the prefix of custom tag.
display.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${name}"/>
Output:
Below are the screenshots of the above example’s output.
Example:
In the below example, first I have set two variables using <c:set> tag and
then I have removed one of them using <c:remove> tag. As you can see in
the output screenshot – when I tried to display both the variables, for the
second attribute the page didn’t get any value and printed the default value
using default attribute of <c:out> tag.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Example of c:remove tag</title>
</head>
<body>
<c:set var="Site" scope="session" value="JavaBook.com"/>
<c:set var="author" scope="session" value="Chandru"/>
<c:remove var="author"/>
<a href="display.jsp">check attributes</a>
</body>
</html>
display.jsp
This above code removes an attribute from all the scopes (page, session,
application, request). In order to be specific we must need to specify the
scope attribute inside <c:remove> tag, like I did below – The below JSTL
statement will remove the variable var from session scope.
<c:remove var="author" scope="session"/>
4.<c: if> tag: This JSTL core tag is used for testing conditions. There are
two other optional attributes for this tag which are var and scope, test is
mandatory.
Syntax:
This is the basic syntax of <c:if> core tag. The set of statements enclosed
within <c:if> tag gets executed if test=”true”. For using this tag we
generally use expression language to evaluate an relational expression. We
use EL because it returns boolean value(true/false) after evaluating the
condition and we need the boolean value for test attribute.
<c:if test="${condition}">
...
..
</c:if>
Example of <c:if> tag
In this example we have defined age variable using <c:set> tag and then we
are checking the eligibility of voting by using <c:if> tag.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>JSTL c:if Tag Example</title>
</head>
<body>
<c:set var="age" value="26"/>
<c:if test="${age >= 18}">
<c:out value="You are eligible for voting!"/>
</c:if>
<c:if test="${age < 18}">
<c:out value="You are not eligible for voting!"/>
</c:if>
</body>
</html>
Output:
<c:if> attributes
Above we have seen the basic usage of <c:if> where we have used only
the test attribute. However there are two other optional attributes for this
tag which are var and scope. Using these attributes you can simply store
the test results in a variable within a specified scope.
var: Variable name in which the test result would be stored.
scope: It defines the scope for storing the value. For e.g. if its session
the stored var value can be accessed till the session is active.
An example of var and scope attribute
Storing the test result in variable res in request scope. For printing the value
we have given requestScope.res as the variable is stored in request however
you can even give variable name(res) alone, it would work fine.
<c:if test="${17 >= 18}" var="res" scope="request">
</c:if>
<c:out value="${requestScope.res}"/>
Syntax:
The basic structure looks like this –
<c:choose>
<c:when test="${condition1}">
//do something if condition1 is true
</c:when>
<c:when test="${condition2}">
//do something if condition2 is true
</c:when>
<c:otherwise>
//Statements which gets executed when all <c:when> tests are false.
</c:otherwise>
</c:choose>
Example:
In this example we have three numbers and we are comparing them using
these three core tags. Example is pretty simple to understand. Screenshot of
output is provided after the example’s code.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>c:choose, c:when and c:otherwise Tag Example</title>
</head>
<body>
<c:set var="number1" value="${222}"/>
<c:set var="number2" value="${12}"/>
<c:set var="number3" value="${10}"/>
<c:choose>
<c:when test="${number1 < number2}">
${"number1 is less than number2"}
</c:when>
<c:when test="${number1 <= number3}">
${"number1 is less than equal to number2"}
</c:when>
<c:otherwise>
${"number1 is largest number!"}
</c:otherwise>
</c:choose>
</body>
</html>
Output:
Syntax:
<c:catch var ="variable_name">
//Set of statements in which exception can occur
</c:catch>
Example
In this example we are intentionally throwing arithmetic exception by
dividing an integer with zero and then we are printing
the errormsg variable (which contains the exception message)
using Expression language (EL).
9. <c:import> tag: This JSTL core tag is used for importing the content
from another file/page to the current JSP page. Attributes – var, URL and
scope.
JSTL <c:import> Core Tag
JSTL <c:import> tag is used for importing the content from another
file/page to the current JSP page.
Syntax:
<c:import var="variable_name" url="relative_url"/>
Attributes of <c:import>
url: It’s mandatory attribute and needs to be mentioned always.
var: It is an optional attribute if this is not specified then the imported
data will be printed on the current page. For e.g. the statement
<c:import url=”/file.jsp” /> would print the data of file.jsp on the client
(browser).
scope: It is also optional. If we are using var attribute then scope can be
used along with it to specify the scope of the data stored in the variable.
Example:
This is a page which has some data. We will import this page in index.jsp
page.
display.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="Chandru"/>
<c:out value="JavaBook.com" />
<c:out value="This is just a String" />
index.jsp
Here we are importing the data from display.jsp into a variable mydata and
then we are displaying it on browser using <c:out> tag.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title> JSTL c:import Tag Example</title>
</head>
<body>
<c:import var="mydata" url="/display.jsp"/>
<c:out value="${mydata}"/>
</body>
</html>
Output:
Chandru javabook.com This is just a string
10. <c:forEach> tag: This tag in JSTL is used for executing the same
set of statements for a finite number of times.
Example
In this example we are printing value of variable counter in loop using
<c:forEach> tag. The loop is starting from value 1 (mentioned
in begin attribute) and ending at value 10 (value of end attribute).
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Example c:forEach tag in JSTL</title>
</head>
<body>
<c:forEach var="counter" begin="1" end="10">
<c:out value="${counter}"/>
</c:forEach>
</body>
</html>
Output:
<c:forTokens> tag
Syntax of <c:forEach>
<c:forTokens items="value(s)" delims="delimiter" var="variable_name">
//Set of statements
</c:forTokens>
Example
In this example we are splitting the strings into multiple substrings using
delimter dot(‘.’).
javabook
com
11. <c:forTokens> tag: It is used for iteration but it only works with
delimiter.
Note:Read the same full example from 10
12.<c:param> tag: This JSTL tag is mostly used with <c:url> and
<c:redirect> tags. It adds parameter and their values to the output of these
tags.
JSTL <c:param> Core Tag
<c:param> JSTL tag is mostly used with <c:url> and <c:redirect> tags.
Basically it adds parameter and their values to the output of these tags. In
this tutorial we will see how the <c:param> tag can be used with <c:url>
and <c: redirect> tags.
Syntax:
<c:param name="parameter_name" value="parameter_value"/>
Attributes of <c:param> tag
name: To specify the name of the parameter.
value: To specify the value of the parameter.
Example:
In this example we are using <c:param> tag for adding parameters to the
resultant URL.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>JSTL c:param Tag Example</title>
</head>
<body>
<c:url value="/mypage.jsp" var="completeURL">
<c:param name="Id" value="736"/>
<c:param name="user" value="chandru"/>
</c:url>
${completeURL}
</body>
</html>
Output:
/Javabook/mypage.jsp?Id=736&user=chandru
display.jsp
USER ID IS: ${param.UserId}
USER NAME IS: ${param.UserName}
Output:
USER ID IS: 222 SUER NAME IS:ChandruBabu
13. <c:url> tag: It is used for url formatting or url encoding. It converts a
relative url into a application context url. Optional attributes var, context
and scope.
JSTL <c:url> Core Tag
<c:url> JSTL tag is used for url formatting or you can say url encoding.
This is mainly used when we need to open a JSP page based on the user
input or based on the value of a variable. It basically converts a relative url
into a application context’s url. It may sound confusing now but follow the
given examples in this tutorial and you will be able to grasp it quite easy.
Syntax:
Basic syntax looks like this – The attribute “value” is a required attribute
for the <c:url> tag
<c:url value="/file1.jsp" />
There are three other optional attributes exist for this tag which are as
follows –
var: Variable name to store the formatted url (resultant url).
context: Used for specifying the application (or project name). Don’t
get it? We will see this with the help of an example later.
scope: The scope in which the var attribute would be stored. It can be
request, page, application or session.
Let us understand the use of this tag and attributes with the help of an
example –
Note: JavaBook is my basics book name (in other words JSP application
name).
Note: The value of the context should always starts with “/” otherwise you
will get the below exception message –
HTTP Status 500 – javax.servlet.ServletException:
javax.servlet.jsp.JspTagException: In URL tags, when the “context”
attribute is specified, values of both “context” and “url” must start with “/”.
<c:url var="myurl" value="/file1.jsp" context="/MyJSPProject"/>
${myurl}
Output:
/MyJSPProject/file1.jsp
Syntax:
<c:redirect url="http://www.anydomainhere.com/samplepage.jsp"/>
This is how the <c:redirect> tag looks like. We just need to provide the
relative address in the URL attribute of this tag and the page will
automatically be redirected the URL provided when it gets loaded.
Example
Here we are redirecting the page to a different url based on the value of the
variable myurl. If the value is 1 page will be redirected to
http://javabook.com and for 2 it will go to http://www.google.com.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title> JSTL c:redirect Tag Example</title>
</head>
<body>
<c:set var="myurl" value="2" scope="request"/>
<c:if test="${myurl<1}">
<c:redirect url="http://javabook.com"/>
</c:if>
<c:if test="${myurl>1}">
<c:redirect url="http://www.google.com"/>
</c:if>
</body>
</html>
Output: Since the value of the variable myurl is 2 the page gets directed to
the http://www.google.com.
JSTL Functions
Following are the tutorial links for useful JSTL functions with examples.
Following Taglib directive should be included in the JSP page in order to
use the JSTL functions.
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Syntax:
boolean fn:contains(String inputstring, String checkstring)
Example of fn:contains()
In this example we are checking whether the new password contains old
password as a sub-string, if it does then we are displaying a message to the
user.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>fn:contains example</title>
</head>
<body>
<c:set var="oldPassword" value="HelloPass"/>
<c:set var="newPassword" value="HelloPassNew" />
<c:if test="${fn:contains(newPassword, oldPassword)}">
<c:out value="New Password should not contain old password as
substring"/>
</c:if>
</body>
</html>
Output:
New Password should not contain old password as substring
2. fn:containsIgnoreCase(): It does a case insensitive check to see
whether the provided string is a sub-string of input.
fn:containsIgnoreCase() – JSTL Function
In this post we are going to see fn:containsIgnoreCase() function which
does a case insensitive check to see whether the provided string is a sub-
string of input or not.
Syntax:
boolean fn:containsIgnoreCase(String input, String checkstring)
Example of fn:containsIgnoreCase()
In this example we are having two strings – string1 & string2. We are
checking whether the string2 is present in string1. If the result is true then
we are displaying a message.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>fn:containsIgnoreCase() example</title>
</head>
<body>
<c:set var="string1" value="Hi This is CHANDRU from JavaBook.com"/>
<c:set var="string2" value="chandru" />
<c:if test="${fn:containsIgnoreCase(string1, string2)}">
<c:out value="Case Insensitive Check: String1 contains string2"/>
</c:if>
</body>
</html>
Output:
Case Insensitive Check:String1 contains string2
3. fn:indexOf(): It is used for finding out the start position of a string in
the provided string. Function returns -1 when string is not found in the
input.
fn:indexOf() – JSTL Function
fn:indexOf() function is used for finding out the start position (index) of a
string in the provided string.
Syntax:
int indexOf(String, String )
The return type of this function is int. It returns the starting position (or
index) of the second string (second argument of the function) in the first
string (first argument of the function).
Points to Note:
The function returns -1 when the string is not found in the input
string.
Function is case sensitive. It treats uppercase and lowercase character
of same alphabet as different.
It returns the index of first occurrence which means if the string is
present in input more than once than the function would return the
index of first occurrence. Refer example.
Example of fn:indexOf() function
In this example we are finding out the index of few strings and displaying
them using EL
Convert the input_string into the output string after escaping html/xml
markup tags.
function return type is String
Argument: input String
fn:escapeXml() Example
Here we have two Strings which have html tags bold(<b>) and italic (<i>).
We are processing them using fn:escapeXml() function.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>JSTL fn:escapeXml() example</title>
</head>
<body>
Message1: <b>Hi This is just a message</b>
<br>Message2: <i>This is an example</i>
<br>Message1 and fn:escapeXml(): ${fn:escapeXml("<b>Hi This is just a
message</b>")}
<br>Message2 and fn:escapeXml(): ${fn:escapeXml("<i>This is an
example</i>")}
</body>
</html>
Output:
As you can see when we used the function on input strings, the html tags
didn’t work and get printed as it is, just like another normal string.
Syntax:
String fn:join(String arrayofstrings, String separator)
It concatenates all the elements of the input array along with the provided
separator in between. The return type of this function is String, it returns the
output string after concatenation.
fn:split()
It splits a given string into an array of substrings. Splitting process
considers the delimiter string which we provide during function call. I.e. we
provide the string and delimiter as arguments to the function and it returns
the array of strings after splitting the input based on the delimiter string.
Syntax:
String[] fn:split(String inputstring, String delimiterstring)
Syntax:
int length(Object)
Return type of this function is int. It returns the length of the object
provided in it as an argument.
Example of fn:length()
Here we are computing the length of the three different strings using the
function.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>JSTL fn:length() example</title>
</head>
<body>
<c:set var="string1" value="This is String1"/>
<c:set var="string2" value="Hi"/>
<c:set var="string3" value="string3"/>
Length of String1 is: ${fn:length(string1)}<br>
Length of String2 is: ${fn:length(string2)}<br>
Length of String3 is: ${fn:length(string3)}
</body>
</html>
Output:
7. fn:startsWith(): It checks the specified string is a prefix of given
string.
fn:trim() and fn:startsWith() JSTL Functions
In this post we are discussing two functions which operates on strings.
These functions are fn:trim() and fn:startsWith(). Function fn:trim()
removes spaces from beginning and end of a string and fn:startsWith()
checks whether the specified string is a prefix of given string.
Syntax:
String fn:trim(String input)
The function returns the string after removing the white spaces from start
and end of the inputString.
Example:
In this example we have a string which has few space characters appended
at the start and end of the string “mymsg” and we are truncating those
spaces using the function.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>fn:trim() example in JSTL</title>
</head>
<body>
<c:set var="mymsg" value=" This is the test String "/>
${fn:trim(mymsg)}
</body>
</html>
Output Screenshot:
fn:startsWith() function in JSTL
It checks whether the given string starts with a particular string value.
Syntax:
boolean fn:startsWith(String input, String prefix)
This function returns a boolean value. It gives true when the string starts
with the given prefix else it returns false.
Example
Here we have one long string and two substrings of it and we are checking
whether the string starts with any of those substrings.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>fn:startsWith example</title>
</head>
<body>
<c:set var="mymsg" value="Example of JSTL function"/>
The string starts with "Example": ${fn:startsWith(mymsg, 'Example')}
<br>The string starts with "JSTL": ${fn:startsWith(mymsg, 'JSTL')}
</body>
</html>
Output:
PFB the output screenshot for above example.
8. fn:endsWith(): fn:endsWith() JSTL function is used for checking the
suffix of a string. It checks whether the given string ends with a particular
string.
fn:endsWith() – JSTL Function
fn:endsWith() function is used for checking the suffix of a string. It checks
whether the given string ends with a particular string. The validation is case
sensitive.
Syntax:
boolean fn:endsWith(input_string, suffix_string)
Syntax:
String fn:substring(String inputstring, int start, int end)
Return type of function: String
inputstring: The string from which a substring needs to be taken
start: Starting position of substring
end: end position of substring
Example – fn:substring() function
In this example we are fetching a substring from a given string by providing
the starting and end positions of the substring.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>JSTL fn:substring() example</title>
</head>
<body>
<c:set var="msg" value="This is an example of JSTL function"/>
${fn:substring(msg, 10, 26)}
</body>
</html>
Output:
example of JSTL
fn:substringAfter()
It returns the part of a given string which lies after a provided string value.
Syntax
String fn:substringAfter(String input, String afterstring)
Example of fn:substringAfter()
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>JSTL fn:substringAfter() example</title>
</head>
<body>
<c:set var="name" value="Rahul Pratap Prasad"/>
${fn:substringAfter(name, "Pr")}
</body>
</html>
Output:
atap Prasad
fn:substringBefore()
It is just opposite of fn:substringAfter function. It returns the the part of
original string which lies before a specified string value.
Syntax:
String fn:substringBefore(String input, String beforestring)
The part of “input” before the “beforestring” will be returned as the output
of this function
Example of fn:substringBefore()
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>JSTL fn:substringBefore() example</title>
</head>
<body>
<c:set var="justastring" value="Hi, How are you??"/>
${fn:substringBefore(justastring, "are")}
</body>
</html>
Output:
Hi, How
Syntax:
String fn:trim(String input)
The function returns the string after removing the white spaces from start
and end of the inputString.
Example:
In this example we have a string which has few space characters appended
at the start and end of the string “mymsg” and we are truncating those
spaces using the function.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>fn:trim() example in JSTL</title>
</head>
<body>
<c:set var="mymsg" value=" This is the test String "/>
${fn:trim(mymsg)}
</body>
</html>
Output:
This is the test String
fn:startsWith() function in JSTL
It checks whether the given string starts with a particular string value.
Syntax:
boolean fn:startsWith(String input, String prefix)
This function returns a boolean value. It gives true when the string starts
with the given prefix else it returns false.
Example:
Here we have one long string and two substrings of it and we are checking
whether the string starts with any of those substrings.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>fn:startsWith example</title>
</head>
<body>
<c:set var="mymsg" value="Example of JSTL function"/>
The string starts with "Example": ${fn:startsWith(mymsg, 'Example')}
<br>The string starts with "JSTL": ${fn:startsWith(mymsg, 'JSTL')}
</body>
</html>
Output: PFB the output screenshot for above example.
Example of fn:toUpperCase()
Here we are converting few strings to their uppercases using the function.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>fn:toUpperCase() example</title>
</head>
<body>
<c:set var="site" value="JavaBook.com"/>
<c:set var="author" value="Chandru"/>
Hi This is ${fn:toUpperCase(author)} from ${fn:toUpperCase(site)}.
</body>
</html>
Output:
The strings author and site got replaced with all uppercase alphabets.
Hi This is CHANDRU from JAVABOOK.COM.
14. fn:toLowerCase(): This function is used for converting an input
string to a lower case string.
fn:toLowerCase() – JSTL Function
This function converts a string into lowercase string. Any upper case
character in the input string is replaced with the corresponding lowercase
character.
Syntax:
String fn:toLowerCase(String input)
Example 0f fn:toLowerCase()
In this example we are applying this function on two strings – one is a
string variable and another is a hard-coded string which is given as an
argument to the function. As you can see in the output that it has replaced
the variable value and hard-coded string value to lowercase. Screenshot of
the output is provided just after this code.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>fn:toLowerCase() example</title>
</head>
<body>
<c:set var="message" value="This is An Example of JSTL Function"/>
${fn:toLowerCase(message)}
${fn:toLowerCase("HELLO")}
</body>
</html>
Output:
This is an Example of jstl function hello
15. fn:replace(): fn:replace() function search for a string in the input and
replace it with the provided string. It does case sensitive processing.
fn:replace() – JSTL Function
It search for a string in the input and replace it with the provided string. The
following is the basic syntax of fn:replace() function.
Syntax:
String fn:replace(String input, String search_for, String replace_with)
Features of JSON:
It is light-weight
It is language independent
Easy to read and write
Text based, human readable data exchange format
Why use JSON?
Standard Structure: As we have seen so far that JSON objects are having
a standard structure that makes developers job easy to read and write code,
because they know what to expect from JSON.
Light weight: When working with AJAX, it is important to load the data
quickly and asynchronously without requesting the page re-load. Since
JSON is light weighted, it becomes easier to get and load the requested data
quickly.
Scalable: JSON is language independent, which means it can work well
with most of the modern programming language. Let’s say if we need to
change the server side language, in that case it would be easier for us to go
ahead with that change as JSON structure is same for all the languages.
JSON vs. XML
Let see how JSON and XML look when we store the records of 4 students
in a text based format so that we can retrieve it later when required.
JSON style:
{"students":[
{"name":"John", "age":"23", "city":"Agra"},
{"name":"Steve", "age":"28", "city":"Delhi"},
{"name":"Peter", "age":"32", "city":"Chennai"},
{"name":"Chandru", "age":"28", "city":"Bangalore"}
]}
XML style:
<students>
<student>
<name>John</name> <age>23</age> <city>Agra</city>
</student>
<student>
<name>Steve</name> <age>28</age> <city>Delhi</city>
</student>
<student>
<name>Peter</name> <age>32</age> <city>Chennai</city>
</student>
<student>
<name>Chandru</name> <age>28</age> <city>Bangalore</city>
</student>
</students>
The above text creates an object that we can access using the variable
chandru. Inside an object we can have any number of key-value pairs like
we have above. We can access the information out of a JSON object like
this:
document.writeln("The name is: " +chandru.name);
document.writeln("his age is: " + chandru.age);
document.writeln("his website is: "+ chandru.website);
},
{
"name" : "Peter",
"age" : "32",
"gender" : "male"
},
{
"name" : "Sophie",
"age" : "27",
"gender" : "female"
}];
To access the information out of this array, we do write the code like this:
document.writeln(students[0].age); //output would be: 29
document.writeln(students[2].name); //output: Sophie
You got the point, right? Let’s carry on with the next type.
"pete" : {
"name" : "Peter",
"age" : "32",
"gender" : "male"
},
"sop" : {
"name" : "Sophie",
"age" : "27",
"gender" : "female"
}
}
Do like this to access the info from above nested JSON objects:
document.writln(students.steve.age); //output: 29
document.writeln(students.sop.gender); //output: female
JSON & JavaScript:
JSON is considered as a subset of JavaScript but that does not mean that
JSON cannot be used with other languages. In fact it works well with PHP,
Perl, Python, Ruby, Java, Ajax and many more.
Just to demonstrate how JSON can be used along with JavaScript, here is an
example:
If you have gone though the above tutorial, you are familiar with the JSON
structures. A JSON file type is .json
How to read data from json file and convert it into a JavaScript object?
We have two ways to do this.
1) Using eval function, but this is not suggested due to security reasons
(malicious data can be sent from the server to the client and then eval in the
client script with harmful effects).
2) Using JSON parser: No security issues plus it is faster than eval. Here is
how to use it:
var chandru = {
"name" : "Chandru",
"age" : "28",
"website" : "Javabook"
};
We are converting the above JSON object to javascript object using JSON
parser:
var myJSObject = JSON.parse(Chandru);
SERVLET TUTORIAL
Servlet Introduction
Servlet is a java program that runs inside JVM on the web server. It is used
for developing dynamic web applications.
The main difference between static and dynamic web page is that static
page as name suggests remains same for all users however a dynamic web
page changes based on the request from client (user’s browser). For
example, consider a web application that shows you two input fields & an
add button and when you enter two numbers and click add, it shows you
another web page that has the result of addition of two numbers, this web
application is dynamic in nature as the second web page that shows you the
result changes based on the user input, it is not static for all users.
However you can very well say that what a servlet does can be done by CGI
(Common Gateway Interface), well its true but here is the thing – CGI has
several limitations such as performance, scalability, reusability etc. that
a servlet does not have. I am not going to discuss CGI in detail but I am
going to tell you, how a servlet is better than CGI.
Limitations of CGI
Server has to create a new CGI process for every client request. For
example, If 100 users are accessing the web application, then the server has
to create 100 CGI processes to handle the request made by them. Since a
server has limited resources, creating new process every time for a new
request is not a viable option, this imposed the limitation on server, due to
that the server cannot handle more than a specified number of users at the
same time.
1.Portable:
As I mentioned above that Servlet uses Java as a programming language,
Since java is platform independent, the same holds true for servlets. For
example, you can create a servlet on Windows operating system that users
GlassFish as web server and later run it on any other operating system like
Unix, Linux with Apache tomcat web server, this feature makes servlet
portable and this is the main advantage servlet has over CGI.
Once a servlet is deployed and loaded on a web server, it can instantly start
fulfilling request of clients. The web server invokes servlet using a
lightweight thread so multiple client requests can be fulling by servlet at the
same time using the multithreading feature of Java. Compared to CGI
where the server has to initiate a new process for every client request, the
servlet is truly efficient and scalable.
3.Robust:
By inheriting the top features of Java (such as Garbage collection,
Exception handling, Java Security Manager etc.) the servlet is less prone to
memory management issues and memory leaks. This makes development of
web application in servlets secure and less error prone.
Servlet API
You need to use Servlet API to create servlets. There are two packages that
you must remember while using API, the javax.servlet package that
contains the classes to support generic servlet (protocol-independent
servlet) and the javax.servlet.http package that contains classes to support
http servlet. You may be wondering what is generic and http servlet, I have
explained them later in this post.
java.lang.Object
|_extended byjavax.servlet.GenericServlet
|_extended byjavax.servlet.http.HttpServlet
In my last guide about Servlet API, I have explained that to create any
Servlet you must implement the Servlet interface directly or indirectly
(indirectly implementation means extending those classes that implements
Servlet interface, These classes are GenericServlet and HttpServlet).
If you are creating protocol dependent servlet such as http servlet then you
should extend HttpServlet class else for protocol independent Servlet you
extend GenericServlet class.
servlet life cycle. Unlike service() method that gets called multiple times
during life cycle, this method is called only once by Servlet container
during the complete life cycle. Once destroy() method is called the servlet
container does not call the service() method for that servlet.
index.html
DemoServlet.java
import java.io.*;
import javax.servlet.*;
public class DemoServlet implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
System.out.println("Initialization complete");
}
web.xml
<web-app>
<servlet>
<servlet-name>Javabook</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Javabook</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
GenericServlet Class
GenericServlet Class with example
While discussing Servlet API, I have discussed little bit about Generic
Servlet. In this article, I will discuss Generic Servlet in detail.
Example of GenericServlet
I am using Eclipse IDE for this example. Create New “Dynamic Web
Project” from the Eclipse file menu.
Note:
Note:I have explained all the steps for creating Servlet in Eclipse IDE,
however if you are unfamiliar with Eclipse and don’t have it installed on
your system then refer this guide: How to Install Eclipse, configure
tomcat and run your First Servlet Application using Eclipse.
Project structure (or you can hierarchy) would look like this, once you are
done creating all the following files in IDE.
index.html
We are creating an html file that would call the servlet once we click on the
link on web page. Create this file in WebContent folder. The path of the file
should look like this: WebContent/index.html
index<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Http Servlet Demo</title>
</head>
<body>
<a href="welcome">Click to call Servlet</a>
</body>
</html>
ExampleGeneric.java
Now, we are creating a Generic Servlet by extending GenericServlet class.
When creating a GenericServlet you should always override service()
method. Right click on the src folder and create a new class file, name the
file as ExampleGeneric. The file path should look like this: Java
Resouces/src/default package/ExampleGeneric.java
import java.io.*;
import javax.servlet.*;
web.xml
This file can be found at this path WebContent/WEB-INF/web.xml. In this
file we will map the Servlet with the specific URL. Since we are calling
welcome page upon clicking the link on index.html page so we are mapping
the welcome page to the Servlet class we created above.
<web-app>
<display-name>JavaBookServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyHttpServlet</servlet-name>
<servlet-class>ExampleHttpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Output:
Screen after you click the link in first screen:
I have already discussed in the Generic Servlet article that you should
always use HttpServlet instead of the GenericServlet. HttpServlet is easier
to work with, and has more methods to work with than GenericServlet.
Http Servlet example
I am using Eclipse IDE for this example. Create New “Dynamic Web
Project” from the Eclipse file menu.
Note:I have explained all the steps for creating Servlet in Eclipse IDE,
however if you are unfamiliar with Eclipse and don’t have it installed on
your system then refer this guide: How to Install Eclipse, configure
tomcat and run your First Servlet Application using Eclipse.
Project structure (or you can hierarchy) would look like this, once you are
done creating all the following files in IDE.
index.html
We are creating an html file that would call the servlet once we click on the
link on web page. Create this file in WebContent folder. The path of the file
should look like this: WebContent/index.html
index<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Http Servlet Demo</title>
</head>
<body>
<a href="welcome">Click to call Servlet</a>
</body>
</html>
ExampleHttpServlet.java
Now, we are creating a Http Servlet by extending HttpServlet class. Right
click on the src folder and create a new class file, name the file as
ExampleHttpServlet. The file path should look like this: Java
Resources/src/default package/ExampleHttpServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Creating Http Servlet by Extending HttpServlet class
public class ExampleHttpServlet extends HttpServlet
{
private String mymsg;
public void init() throws ServletException
{
mymsg = "Http Servlet Demo";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
// Setting up the content type of web page
response.setContentType("text/html");
// Writing the message on the web page
PrintWriter out = response.getWriter();
out.println("<h1>" + mymsg + "</h1>");
out.println("<p>" + "Hello Friends!" + "</p>");
}
public void destroy()
{
// Leaving empty. Use this if you want to perform
//something at the end of Servlet life cycle.
}
}
web.xml
<web-app>
<display-name>JavaBookServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyHttpServlet</servlet-name>
<servlet-class>ExampleHttpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Run the project:
Right click on the index.html, run on server.
Output:
Hello Friends
Methods of HttpServlet class
1. protected void doGet(HttpServletRequest req, HttpServletResponse
resp): This method is called by servlet service method to handle the HTTP
GET request from client. When overriding this method, read the request
data, write the response headers, get the response’s writer or output stream
object, and finally, write the response data.
Note:
Get back from here:
Generic Servlet
HttpServlet class
Download Eclipse IDE
Install Eclipse on Windows
Go to this link https://www.eclipse.org/downloads. Under “Get Eclipse
Oxygen” ❯ Click “Download Packages” ❯ Download “Eclipse IDE for Java
Developers”. You would see two options on the right side (32 bit and 64
bit), click on 32 bit if you system is 32 bit else click on 64 bit. This will
download a zipped file on your system.
To install Eclipse, unzip the downloaded file and copy the unzipped folder
to the desired location
Install Eclipse on Mac OS X
Go to this link https://www.eclipse.org/downloads. Under “Get Eclipse
Oxygen” ❯ Click “Download Packages” ❯ Download “Eclipse IDE for Java
Developers”. To download click on 64 bit and it would download a TAR
file.
Once download is finished double click on the TAR file, it would extract
the contents of the file to a folder. Drag the folder to “Applications” folder.
To launch the Eclipse, click on Eclipse icon in the Eclipse folder. Mac
users can drag this to the dock area to quickly launch Eclipse from desktop,
similarly Windows can create a shortcut of Eclipse on desktop.
Installing and configuring Apache tomcat server in Eclipse
In order to run Servlet in Eclipse IDE, you need to have Apache tomcat
Server configured in Eclipse IDE.
If you don’t have it then refer this tutorial: How to download and
configure Apache Tomcat Server in Eclipse IDE.
Note: The link I have provided above belongs to JSP tutorials but the steps
are same for Servlets as well.
Creating Servlet in Eclipse IDE
Step 1: Create a Project:
Lets create a Servlet application in Eclipse. Open Eclipse and then click
File ❯ New ❯ Click Dynamic Web Project.
If you do not see dynamic web project option in Eclipse then refer this
tutorial: How to fix “Dynamic Web project” missing in Eclipse issue
MyServletDemo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaBook Servlet Demo</title>
</head>
<body>
<a href="welcome">Click to call Servlet</a>
</body>
</html>
Edit web.xml file
This file can be found at this path WebContent/WEB-INF/web.xml. In this
file we will map the Servlet with the specific URL. Since we are calling
welcome page upon clicking the link on index.html page so we are mapping
the welcome page to the Servlet class we created above.
<web-app>
<display-name>JavaBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Output:
Step 1: Download
Note:If you don’t see the apache option in the add server list that means
you are missing few adapters in Eclipse, refer this tutorial to fix the issue:
How to fix “no apache tomcat adapter in Eclipse” issue
You will be presented with a window as shown in the image below. Click
browse and select the the folder that you have extracted from the zip file in
Step 2.
Click finish.
That’s it you have successfully configured the tomcat server in Eclipse, you
can now run the JSP in Eclipse.
Please note that the link I have provided would work on Eclipse mars only
so change the link according to your Eclipse version, for example for the
Eclipse Kepler the link would be
http://download.eclipse.org/releases/kepler
Step 3: Scroll down to find “Web, XML, Java EE and OSGI
Enterprise Development” option and expand it.
Step 4: Select the following three options under “Web, XML, Java EE and
OSGI Enterprise Development”
Eclipse Java EE Developer Tools
Eclipse Java Web Developer Tools
Eclipse Web Developer Tools
Step 5: Click next and you would see that the software are installing. Wait
for some time and then a popup would ask your permission to restart the
Eclipse. Restart it and you would find the dynamic web project option
under project list.
Note:
Get back from here:
How to create and run Servlet in Eclipse IDE
Solution – No Apache Tomcat Adapter option in
Eclipse IDE
Sometimes you don’t find the Apache option when you try to add the
tomcat server first time in the Eclipse. It happens when you are missing few
adapters. In this tutorial, I will tell you how to fix this issue.
Use the above link only when you are using Eclipse mars version,
else give the link as per your Eclipse version. For example, Eclipse Kepler
users would give this link in the Work with field:
http://download.eclipse.org/releases/kepler
Scroll down until you see “Web, XML, Java EE and OSGi Enterprise
Development”, then expand this and add the following adapters:
JST Server Adapters
JST Server Adapters Extensions
Step 3: Click Next and you would see the following screen. Click
next again.
Note:
Get back from here
How to configure Apache Tomcat Server in
Eclipse IDE
Servlet Life Cycle
Servlet life cycle can be described as a series of steps through which a
servlet goes during its life span, starting from loading till it gets destroyed.
Before I start explaining the life cycle of Servlet, lets discuss few
terminologies that you will encounter while reading this guide. It is
important to learn what each term means, this will help you understand
things faster.
Note: The servlet tutorials you find in this website uses apache tomcat web
server. Although I mentioned it as web server, it is in fact a web server and
web container both. (As mentioned above web container is a part of web
server).
Life Cycle of Servlet
Servlet life cycle contains five steps: 1) Loading of Servlet 2) Creating
instance of Servlet 3) Invoke init() once 4) Invoke service() repeatedly for
each client request 5) Invoke destroy()
For those who are wondering what is instance and invoke means: Instance
and objects are same thing. Invoking a method means calling a method, it is
just a fancy word that we use in programming world in place of calling :)
Let’s back to the main topic. Here are the five steps of servlet life cycle.
Once all the servlet classes are instantiated, the init() method is invoked for
each instantiated servlet. This method initializes the servlet. There are
certain init parameters that you can specify in the deployment descriptor
(web.xml) file. For example, if a servlet has value >=0 then its init() method
is immediately invoked during web container startup.
Note: The init() method is called only once during the life cycle of
servlet.
For example if its a Get Request the service() method would dispatch the
request to the doGet() method by calling the doGet() method with request
parameters. Similarly the requests like Post, Head, Put etc. are dispatched to
the corresponding handlers doPost(), doHead(), doPut() etc. by service()
method of servlet.
Note: Unlike init() and destroy() that are called only once, the service()
method can be called any number of times during servlet life cycle. As long
as servlet is not destroyed, for each client request the service() method is
invoked.
Out of all the 5 steps in life cycle, this is the only step that
executes multiple times.
Note:
Servlet Interface
Working of Servlet
Before I start explaining how the servlet works, lets get familiar with these
three terms.
Web Server: it can handle HTTP Requests send by clients and responds the
request with an HTTP Response.
rather than the steps of life cycle. I would highly recommend you to read
this to have in depth knowledge of how the servlet actually works.
2) Once the servlet is loaded, the servlet container creates the instance of
servlet class. For each instantiated servlet, its init() method is invoked.
For example if server receives a Get Request the service() method would
dispatch the request to the doGet() method by calling the doGet() method
with request parameters. Similarly the requests like Post, Head, Put etc. are
dispatched to the corresponding handlers doPost(), doHead(), doPut() etc.
by service() method of servlet.
4) When servlet container shuts down, it unloads all the servlets and calls
destroy() method for each initialized servlets.
Welcome-file-list tag in web.xml file of Project
Have you ever seen <welcome-file-list> tag in your web.xml file and
wondering what it is? In this text, I will explain what is this tag and why we
use it.
The tag <welcome-file-list> is used for specifying the files that needs to be
invoked by server by default, if you do not specify a file name while
loading the project on browser.
For e.g. You have created a project named “MyServletProject” and you
have few html pages and servlet classes defined in the project. However in
browser you have given the url like this:
http://localhost:8080/MyServletProject
<web-app>
....
<welcome-file-list>
<welcome-file>myhome.htm</welcome-file>
<welcome-file>myindex.htm</welcome-file>
<welcome-file>mydefaultpage.htm</welcome-file>
</welcome-file-list>
....
</web-app>
Based on the welcome file list, server would look for the myhome.htm page
if this doesn’t exist then the second welcome file myindex.html and so on
till it finds a valid welcome file.
<web-app>
…
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.Javabook.DemoServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
…
</web-app>
If I did not specify the <load-on-startup>, the web container would not have
loaded the servlet until it receives a request for DemoServlet servlet class.
Since I have specified a value >=0, this servlet (DemoServlet class) would
be loaded on the startup.
Note:value >= 0 means that the servlet is loaded when the web-app is
deployed or when the server starts, if the value < 0 then servlet would be
loaded whenever the container feels like.
<servlet>
<servlet-name>MyServlet1</servlet-name>
<servlet-class>com.Javabook.DemoServlet1</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
<servlet>
<servlet-name>MyServlet2</servlet-name>
<servlet-class>com.Javabook.DemoServlet2</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>MyServlet3</servlet-name>
<servlet-class>com.Javabook.DemoServlet3</servlet-class>
<load-on-startup>-2</load-on-startup>
</servlet>
…
</web-app>
In this example we have three Servlets specified in the web.xml file, since
servlet classes DemoServlet1 and DemoServlet2 has load-on-startup value
>=0, they both will be loaded as soon as the server starts. However servlet
class DemoServlet2 would be loaded before the DemoServlet1 class
because it has lower load-on-startup value.
First we will see an example and then we will see the list of methods
available in the ServletRequest interface:
Example 1: ServletRequest getParameter() method to display
the user input
In this example I am demonstrating the use of getParameter() method that
returns the value of the given parameter.
In this html form, we are taking user input (name and age) and storing them
in the parameters uname and uage respectively.
index.html
MyServletDemo.java
In this servlet class we are getting the value of the parameters by using
getParameter() method, this method belongs to the ServletRequest
interface. In this example we have HttpServletRequest as a parameter of
doGet() method, HttpServletRequest extends ServletRequest interface thats
why the getParameter() method is available to the req object.
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class MyServletDemo extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
Web.xml
This is your deployment descriptor file that maps the servlet to the url.
Since our form has details page as action, we mapped the servlet class to the
details page.
<web-app>
<display-name>JavaBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>JavaBook</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JavaBook</servlet-name>
<url-pattern>/details</url-pattern>
</servlet-mapping>
</web-app>
Output:
Screen 1:
Screen 2 that appears upon clicking submit:
index.html
MyServletDemo.class
import java.io.IOException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServletDemo extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
PrintWriter pwriter=res.getWriter(); res.setContentType("text/html");
Enumeration en=req.getParameterNames();
while(en.hasMoreElements())
{
Object obj=en.nextElement();
String param=(String)obj;
String pvalue=req.getParameter(param);
pwriter.print("Parameter Name: "+param+
" Parameter Value: "+pvalue);
}
pwriter.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>JavaBook</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JavaBook</servlet-name>
<url-pattern>/details</url-pattern>
</servlet-mapping>
</web-app>
Output:
Parameter Name:uname Parameter Value:ChandruParameter Name:uage
Parameter Value:30
HeaderDetails.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Enumeration en = request.getHeaderNames();
while (en.hasMoreElements()) {
String hName = (String) en.nextElement();
String hValue = request.getHeader(hName);
pwriter.println("<b>"+hName+": </b>"
+hValue + "<br>");
}
}
}
web.xml
<web-app>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>JavaBook</servlet-name>
<servlet-class>HeaderDetails</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JavaBook</servlet-name>
<url-pattern>/headinfo</url-pattern>
</servlet-mapping>
</web-app>
Output:
Methods of ServletRequest interface
String getParameter(String name): It returns the value of the given
parameter as String or null if the given parameter does not exist.
Now, we are taking the same example with forward. We have same pages X
and Y. In page X, we have forward tag. In this case the control will be in
page X till it encounters forward, after this the control will be transferred to
page Y. The main difference here is that the control will not return back to
X, it will be in page Y till the end of it.
In this case the final response to the client will be send by page Y.
Example:
In this example, I will be using both the methods include and forward.
Using include method, I will be changing the content of current page and
when I’m ready to transfer the control to the next page, I will use forward
method.
index.html
Validation.java
import java.io.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validation extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name=request.getParameter("uname");
String pass=request.getParameter("upass");
if(name.equals("Chandru") &&
pass.equals("Javabook"))
{
RequestDispatcher dis=request.getRequestDispatcher("welcome");
dis.forward(request, response);
}
else
{
pwriter.print("User name or password is incorrect!");
RequestDispatcher dis=request.getRequestDispatcher("index.html");
dis.include(request, response);
}
}
}
WelcomeUser.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name=request.getParameter("uname");
pwriter.print("Hello "+name+"!");
pwriter.print(" Welcome to Javabook.com");
}
web.xml
<web-app>
<display-name>JavaBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Validation</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>WelcomeUser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/loginPage</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Output:
Entering wrong credentials:
Error screen:
Welcome screen on entering correct user name and password:
ServletConfig Interface
ServletConfig Interface with example
Servlet Container creates ServletConfig object for each Servlet during
initialization, to pass information to the Servlet. This object can be used to
get configuration information such as parameter name and values from
deployment descriptor file(web.xml).
Methods of ServletConfig interface
public String getInitParameter(String name): Returns the value of given
parameter as String, or null if the given parameter doesn’t exist in web.xml.
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Enumeration;
response.setContentType("text/html;charset=UTF-8");
PrintWriter pwriter = response.getWriter();
ServletConfig sc=getServletConfig();
Enumeration<String> e=sc.getInitParameterNames();
String str;
while(e.hasMoreElements()) {
str=e.nextElement();
pwriter.println("<br>Param Name: "+str);
pwriter.println(" value: "+sc.getInitParameter(str));
}
}
}
web.xml
<web-app>
<display-name>JavaBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>MyName</param-name>
<param-value>Chandru</param-value>
</init-param>
<init-param>
<param-name>MyWebsite</param-name>
<param-value>Javabook.com</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/scdemo</url-pattern>
</servlet-mapping>
</web-app>
Output:
ServletContext sc;
public void init(ServletConfig scfg)
{
sc=scfg.getServletContext();
}
Context Initialization parameters are the parameter name and value pairs
that you can specify in the deployment descriptor file (the web.xml file).
Here you can specify the parameters that will be accessible to all the
servlets in the web application.
When we deploy the Web application, the Servlet container reads the
initialization parameter from the web.xml file and initializes the
ServletContext object with it. We can use
the getInitParameter()and getInitParameterNames() methods of the
ServletContext interface to get the parameter value and enumeration of
parameter names respectively.
For example, here I have specified the parameter email_id with the value,
since this is common to all the servlets, you can get the parameter name and
value in any servlet.
<context-param>
<param-name>email_id</param-name>
<param-value>[email protected]</param-value>
</context-param>
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse
response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter pwriter=response.getWriter();
web.xml
<web-app>
<servlet>
<servlet-name>JavaBook</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>uname</param-name>
<param-value>Chandruprasad</param-value>
</context-param>
<context-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</context-param>
<servlet-mapping>
<servlet-name>JavaBook</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
Output:
public String getServerInfo(): eturns the name and version of the servlet
container on which the servlet is running.
The response object allows you to format and send the response back to the
client. First we will see the commonly used methods in the ServletReponse
interface and then we will see an example.
Method of ServletResponse interface
1) String getCharacterEncoding(): It returns the name of the MIME charset
used in body of the response sent to the client.
10) void flushBuffer(): Forces any content in the buffer to be written to the
client.
index.html
MyServletDemo.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class MyServletDemo extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
String name=req.getParameter("uname");
pwriter.println("User Details Page:");
pwriter.println("Hello "+name);
pwriter.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/mydetails</url-pattern>
</servlet-mapping>
</web-app>
Output:
User name:Chandrurasad
Screen 2:
The HttpSession stays alive until it has not been used for more than the
timeout value specified in tag in deployment descriptor file( web.xml). The
default timeout value is 30 minutes, this is used if you don’t specify the
value in tag. This means that when the user doesn’t visit web application
time specified, the session is destroyed by servlet container. The subsequent
request will not be served from this session anymore, the servlet container
will create a new session.
You can store the user information into the session object by using
setAttribute() method and later when needed this information can be
fetched from the session. This is how you store info in session. Here we are
storing username, emailid and userage in session with the attribute name
uName, uemailId and uAge respectively.
session.setAttribute("uName", "ChandruPrasad");
session.setAttribute("uemailId", "[email protected]");
session.setAttribute("uAge", "30");
This First parameter is the attribute name and second is the attribute value.
For e.g. uName is the attribute name and ChandruPrasad is the attribute
value in the code above.
<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
String myName=(String)session.getAttribute("uname");
String myPass=(String)session.getAttribute("upass");
pwriter.print("Name: "+myName+" Pass: "+myPass);
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Output:
First Screen:
After clicking Submit:
Name:Chandru Pass:chandru
Cookies in Servlet
Cookies in Servlet with example
Here we will discuss Cookies which is also used for session management.
Let’s recall few things here from last tutorial so that we can relate sessions
and cookies. When a user visits web application first time, the servlet
container crates new HttpSession object by calling request.getSession(). A
unique Id is assigned to the session. The Servlet container also sets a
Cookie in the header of the HTTP response with cookie name and the
unique session ID as its value.
The cookie is stored in the user browser, the client (user’s browser) sends
this cookie back to the server for all the subsequent requests until the cookie
is valid. The Servlet container checks the request header for cookies
and get the session information from the cookie and use the associated
session from the server memory.
The session remains active for the time specified in tag in web.xml. If tag in
not set in web.xml then the session remains active for 30 minutes. Cookie
remains active as long as the user’s browser is running, as soon as the
browser is closed, the cookie and associated session info is destroyed. So
when the user opens the browser again and sends request to web server, the
new session is being created.
Types of Cookies
We can classify the cookie based on their expiry time:
1. Session
2. Persistent
1)SessionCookies:
Session cookies do not have expiration time. It lives in the browser
memory. As soon as the web browser is closed this cookie gets destroyed.
2)Persistent Cookies:
Unlike Session cookies they have expiration time, they are stored in the
user hard drive and gets destroyed based on the expiry time.
How to send Cookies to the Client
Here are steps for sending cookie to the client:
c.setMaxAge(1800);
response.addCookie(c);
How to read cookies
Cookie c[]=request.getCookies();
//c.length gives the cookie count
for(int i=0;i<c.length;i++){
out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());
}
Example of Cookies in java servlet
index.html
<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
//Reading cookies
Cookie c[]=request.getCookies();
//Displaying User name value from cookie
pwriter.print("Name: "+c[1].getValue());
//Displaying user password value from cookie
pwriter.print("Password: "+c[2].getValue());
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
web.xml
<web-app>
<display-name>JavaBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Output:
Welcome Screen:
Name:ChandruprasadPassword:Javabook
Methods of Cookie class
public void setComment(String purpose): This method is used for setting
up comments in the cookie. This is basically used for describing the
purpose of the cookie.
public void setMaxAge(int expiry): Sets the maximum age of the cookie
in seconds.
public int getMaxAge(): Gets the maximum age in seconds of this Cookie.
By default, -1 is returned, which indicates that the cookie will persist until
browser shutdown.
public String getName(): Returns the name of the cookie. The name
cannot be changed after creation.