This tutorial is aimed for those developers, who have some basics of JSP. Do read Java Server Pages (I) before going through this one. In the last tutorial, I have talked about basics of JSP pages with a lot of examples. I introduced Request object at the last part of the tutorial.
In this tutorial, I will talk about other implicit objects available in JSP along with Java beans.
Response object
HTTP response data is denoted by the response object. Response object handles the output of the client. It corresponds to http.HttpServletResponse. It should be noted that response object is used by cookies and HTTP headers.
There are many methods available for response object and they are very useful.
|
Code:
|
setContentType()
addCookie(Cookie cookie)
addHeader(String name, String value)
containsHeader(String name)
setHeader(String name, String value)
sendRedirect(String)
sendError(int status_code) |
Response object - setContentType()
This method is used to set the MIME type and character encoding for the page.
Syntax:
|
Code:
|
response.setContentType(); |
Example:
|
Code:
|
response.setContentType("text/html"); |
Response object - addCookie(Cookie cookie)
To add a cookie to the response, addCookie method is used. We may store useful information in cookies for later use and this method is perfect for our needs.
Syntax:
|
Code:
|
response.addCookie(Cookie cookie) |
Example:
|
Code:
|
response.addCookie(Cookie exforsys); |
Now I will present a meaningful example to how to set and retrieve cookies.
The following form is used to take username form the user. When submitted, it posts the username to setcookies.jsp, which is responsible for storing the information into cookie.
cookieform.jsp
|
Code:
|
<%@ page language="java" %>
<html>
<head>
<title>Cookie Input Form</title>
</head>
<body>
<form method="post" action="setcookie.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
</body> |
The page below gets the posted values using request object and stores it into a cookie. It then displays a link to showcookievalue.jsp, which shows the value stored in the cookie.
setcookie.jsp
|
Code:
|
<%@ page language="java" import="java.util.*"%>
<%
String username=request.getParameter("username");
if(username==null) username="";
Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
%>
<html>
<head>
<title>Cookie Saved</title>
</head>
<body>
<p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p>
</body> |
Presented below is a page that reads contents for the cookies and displays it to the user.
showcookievalue.jsp
|
Code:
|
<%@ page language="java" %>
<%
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i];
break;
}
}
}
%>
<html>
<head>
<title>Show Saved Cookie</title>
</head>
<body>
<%
if (myCookie == null) {
%>
No Cookie found with the name <%=cookieName%>
<%
} else {
%>
<p>Welcome: <%=myCookie.getValue()%>.
<%
}
%>
</body> |
Response object - addHeader(String name, String value)
response object provides addHeader() method to write the header as a pair of name and value to the response.
Syntax:
|
Code:
|
response.addHeader(String name, String value) |
Example:
|
Code:
|
response.addHeader("Author", "JavaTutorial");
response.addHeader("Cache-Control", "max-age=15"); |
Response object - containsHeader(String name)
Sometimes we want to check whether the response already includes the header given as parameter. For this, containsHeader method is used. It returns true, if the named response header is set and return false if the named response header is not set. So we can say that containsHeader method is used to test the presence of a header before setting its value. Syntax:
|
Code:
|
response.containsHeader(String name) |
Response object - setHeader(String name, String value)
This method of response object is used to create an HTTP Header with the name and value given as string. The original value is replaced by the current value given as parameter in this method if the header is already present.
Syntax:
|
Code:
|
response.setHeader(String name, String value) |
Example:
|
Code:
|
response.setHeader("Content_Type","text/html"); |
Response object - sendRedirect(String)
We may forward a request to a new target using sendRedirect method. Thing to note is that if the JSP executing has already sent page content to the client, then the sendRedirect() method of response object will not work and will fail.
Syntax:
|
Code:
|
response.sendRedirect(String) |
Example:
|
Code:
|
response.sendRedirect("http://www.yahoo.com"); |
Response object - sendError(int status_code)
Sometimes we need to send an error response to the client containing the specified status code given in parameter. For this, setError method of response object is used.
Syntax:
|
Code:
|
response.sendError(int status_code) |
Out object
out object corresponds to Javax.servlet.jsp.JspWriter and it denotes the output stream in the context of page. It is used to write to the JSP's output stream. We display the contents to the users on the JSP pages using out object. Since it is an implicit object, we do not need to initialize it, it is there to be used.
Following are useful methods of out object:
|
Code:
|
clear
clearBuffer
flush
isAutoFlush
getBufferSize
getRemaining
newLine
print
println |
Out object – clear
Clear method is used to clear the output buffer. It does not write any content to the client and it throws an exception if the buffer was flushed.
Syntax:
Out object – clearBuffer
This method is pretty much the same as clear method. It clears the output buffer. But it differs from clear method since it does not throw an exception if the buffer was flushed.
Syntax:
Out object – flush
If you want to flush the buffer and write contents to the client, then the flush method of out object will serve the purpose. The flush method of out object flushes the buffer by writing the contents to the client.
Syntax:
Example:
|
Code:
|
out.flush();
jsp:forward page="welcome.jsp" |
Out object – getBufferSize
The getBufferSize method returns the size of the buffer in bytes. It return 0 if the output is not buffered.
Syntax:
|
Code:
|
out.getBufferSize() |
Example:
|
Code:
|
if (out.getBufferSize() != 0)
out.getBufferSize(); |
Out object – getRemaining
The getRemaining method of out object is used to return the number of empty bytes in the buffer.
Syntax:
|
Code:
|
out.getRemaining(); |
Out object - newLine
In order to move to a new line, newLine method of out object is used.
Syntax:
Example:
|
Code:
|
out.write("Welcome!!!");
out.newLine();
out.write("to Java.");
out.newLine(); |
Out object - print
To write or print, we use print method of out object. It is a very useful method and is used to print contents for the users.
Syntax:
Example:
|
Code:
|
out.print("Welcome!!!");
out.print("To Java"); |
Out object - println
If you want to write the value to the output, including the newline character, then println method of out object should be used.
Syntax:
Example:
|
Code:
|
out.println("The Output is:" + var); |
JSP Session Object
Session Object is another implicit JSP object that denotes the data associated with a specific session of a user. It is associated to Javax.servlet.http.httpsession.
The connection between client and the server is provided by the session object. It maintains states when there are multiple page requests. If the user is navigating between multiple pages, and you need to store some data associated with that user, then session object helps you in this.
Some useful session object methods are:
|
Code:
|
getAttribute(String name)
getAttributeNames
isNew()
getCreationTime
getId
invalidate()
getLastAccessedTime
getMaxInactiveInterval
removeAttribute(String name)
setAttribute(String, object) |
Session object - getAttribute(String name)
The getAttribute method of session object is used to return the object (java.lang.Object) with the specified name given in parameter. If there is no object then a null value is returned.
Syntax:
|
Code:
|
session.getAttribute(String name) |
Example:
|
Code:
|
String userName = (String) session.getAttribute("username"); |
So, as a JSP developer, you may save objects (String, ArrayList, HashList, Vectors etc) into session object and can retrieve whenever you need.
Session object – getAttributeNames
getAttributeNames method of session object is used to get all the stored session objects (current session). It returns an enumeration object and we can iterate through it to deal wit all the session objects.
Syntax:
|
Code:
|
session.getAttributeNames() |
Example:
|
Code:
|
enumObjects = session.getAttributeNames( ) ; |
The above statement returns enumeration of objects, which contains all the unique names stored in the current session object in the enumeration object enumObjects.
Session object – isNew
If a session is new, then isNew method of session object will return true otherwise false.
When a server creates a session and client has not yet acknowledged the session, the server marks it with new. When the client joins a session, the session does not remain new anymore.
Syntax:
PageContext
PageContext object is used to access the page attributes and namespaces associated with a JSP page. It is associated with Javax.servlet.jsp.pagecontex. Review the example below:
|
Code:
|
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%
synchronized (pageContext) {
Class thisClass = getClass();
pageContext.setAttribute("thisClass", thisClass, PageContext.PAGE_SCOPE);
System.out.println("Stored reference");
Class theClass = (Class) pageContext.getAttribute("thisClass", PageContext.PAGE_SCOPE);
System.out.println("The retrieved reference is " + theClass);
}
%>
<html>
<body>
The class that instantiated this JSP is <c:out value="${pageScope.thisClass.name}" />.
</body>
</html> |
Application
This is used to share the data with all application pages. It is associated with Javax.servlet.http.ServletContext. An example of application object is presented below:
|
Code:
|
<%
String theSharedObject = (String) application.getAttribute("message");
%>
<HTML>
<HEAD>
<TITLE>Application Object - Page 2</TITLE>
</HEAD> <BODY>
This page retrieves the message that was stored in the
<i>application</i> object by another page.
<P>
The message is <b><%= theSharedObject %></b>
</BODY>
</HTML> |
Config
The Servlet configuration details are stored in the Config object. The config implicit object is used to access that information. It is associated with Javax.servlet.http.ServletConfig.
Page
A JSP page is denoted by a page object. It is associated with Java.lang.Object.
Java beans
Java beans are simple Java classes that follow some rules:
- Implements java.io.Serializable interface
- Provides no argument constructor
- Provides getter and setter methods for accessing it's properties
An example Java bean class is given below:
|
Code:
|
public class SimpleBean implements java.io.Serializable {
/* Properties */
private String name = null;
private int age = 0;
/* Empty Constructor */
public SimpleBean() {}
/* Getter and Setter Methods */
public String getName() {
return name;
}
public void setName(String s) {
name = s;
}
public int getAge() {
return age;
}
public void setAge(int i) {
age = i;
}
} |
We can use Java beans is JSP and it is very useful to use these classes in normal practice.
Following are the three Java bean tags available in JSP :
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<jsp:useBean>
The useBean tag is used to instantiate the JavaBean class.
Syntax:
|
Code:
|
<jsp:useBean
id="object-name"
scope="page | request | session | application"
type="type-of-object"
class="fully-qualified-classname"
beanName="fully-qualified-beanName"
/> |
Lets discuss the syntax.
id - name of the object. This name is the name of bean instance and the bean will be referred with this name.
scope - an optional attribute by which you can control when your JavaBean object will be destroyed. Default is page.
type - type of the object
class - a fully qualified class name
beanName - it is also fully qualified class name just like 'class' attribute above. Only difference is that the class name in the case of 'beanName' can be provided at request time.
<jsp:setProperty>
The setProperty tag is used to set the value of one or all the properties of a Java bean.
Syntax:
|
Code:
|
<jsp:setProperty
name="id-of-the-JavaBean"
property="name-of-property"
param="name-of-request-parameter-to-use"
value="new-value-of-this-property"
/> |
Example:
|
Code:
|
<jsp:setProperty name="mybean" property="*" />
<jsp:setProperty name="mybean" property="username" />
<jsp:setProperty name="mybean" property="username" value="Steve" /> |
<jsp:getProperty>
The getProperty tag is used to retrieve the value of a given property from the given JavaBean.
Syntax:
|
Code:
|
<jsp:getProperty
name="name-of-the-object"
property="name-of-property"
/> |
Example:
|
Code:
|
<jsp:useBean id="calendar" scope="page" class="employee.Calendar" />
<h2>
Calendar of <jsp:getProperty name="calendar" property="username" />
</h2> |
Bean example
Now you now some basics about the beans tags, its time to show an example:
|
Code:
|
<jsp:useBean id="cart" scope="session" class="session.Carts" />
<jsp:setProperty name="cart" property="*" />
<jsp:useBean id="checking" scope="session" class="bank.Checking" >
<jsp:setProperty name="checking" property="balance" value="0.0" />
</jsp:useBean> |
Conclusion
Java server pages are very easy to use and are very productive. They should be used with taglibs and java beans for better results.