Results 1 to 1 of 1
Thread: Java Server Pages (II)
- 03-12-2008, 06:03 PM #1
Member
- Join Date
- Nov 2007
- Posts
- 22
- Rep Power
- 0
Java Server Pages (II)
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.
Response object - setContentType()Java Code:setContentType() addCookie(Cookie cookie) addHeader(String name, String value) containsHeader(String name) setHeader(String name, String value) sendRedirect(String) sendError(int status_code)
This method is used to set the MIME type and character encoding for the page.
Syntax:
Example:Java Code:response.setContentType();
Response object - addCookie(Cookie cookie)Java Code:response.setContentType("text/html");
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:
Example:Java Code:response.addCookie(Cookie cookie)
Now I will present a meaningful example to how to set and retrieve cookies.Java Code:response.addCookie(Cookie exforsys);
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
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.Java 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>
setcookie.jsp
Java 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
Response object - addHeader(String name, String value)Java 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 provides addHeader() method to write the header as a pair of name and value to the response.
Syntax:
Example:Java Code:response.addHeader(String name, String value)
Response object - containsHeader(String name)Java Code:response.addHeader("Author", "JavaTutorial"); response.addHeader("Cache-Control", "max-age=15");
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:
Response object - setHeader(String name, String value)Java Code:response.containsHeader(String name)
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:
Example:Java Code:response.setHeader(String name, String value)
Response object - sendRedirect(String)Java Code:response.setHeader("Content_Type","text/html");
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:
Example:Java Code:response.sendRedirect(String)
Response object - sendError(int status_code)Java Code:response.sendRedirect("http://www.yahoo.com");
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:
Out objectJava Code:response.sendError(int status_code)
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:
Out object – clearJava Code:clear clearBuffer flush isAutoFlush getBufferSize getRemaining newLine print println
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 – clearBufferJava Code:out.clear();
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:
Java Code:out.clearBuffer();
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:Java Code:out.flush();
Out object – getBufferSizeJava Code:out.flush(); jsp:forward page="welcome.jsp"
The getBufferSize method returns the size of the buffer in bytes. It return 0 if the output is not buffered.
Syntax:
Example:Java Code:out.getBufferSize()
Out object – getRemainingJava Code:if (out.getBufferSize() != 0) out.getBufferSize();
The getRemaining method of out object is used to return the number of empty bytes in the buffer.
Syntax:
Out object - newLineJava Code:out.getRemaining();
In order to move to a new line, newLine method of out object is used.
Syntax:
Example:Java Code:out.newLine();
Out object - printJava Code:out.write("Welcome!!!"); out.newLine(); out.write("to Java."); out.newLine();
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:Java Code:out.print();
Out object - printlnJava Code:out.print("Welcome!!!"); out.print("To Java");
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:Java Code:out.println();
JSP Session ObjectJava Code:out.println("The Output is:" + var);
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:
Session object - getAttribute(String name)Java Code:getAttribute(String name) getAttributeNames isNew() getCreationTime getId invalidate() getLastAccessedTime getMaxInactiveInterval removeAttribute(String name) setAttribute(String, object)
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:
Example:Java Code:session.getAttribute(String name)
So, as a JSP developer, you may save objects (String, ArrayList, HashList, Vectors etc) into session object and can retrieve whenever you need.Java Code:String userName = (String) session.getAttribute("username");
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:
Example:Java Code: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.Java Code:enumObjects = session.getAttributeNames( ) ;
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:
PageContextJava Code:session.isNew()
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:
ApplicationJava 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>
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:
ConfigJava 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>
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:
We can use Java beans is JSP and it is very useful to use these classes in normal practice.Java 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; } }
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:
Lets discuss the syntax.Java Code:<jsp:useBean id="object-name" scope="page | request | session | application" type="type-of-object" class="fully-qualified-classname" beanName="fully-qualified-beanName" />
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:
Example:Java 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" />
<jsp:getProperty>Java Code:<jsp:setProperty name="mybean" property="*" /> <jsp:setProperty name="mybean" property="username" /> <jsp:setProperty name="mybean" property="username" value="Steve" />
The getProperty tag is used to retrieve the value of a given property from the given JavaBean.
Syntax:
Example:Java Code:<jsp:getProperty name="name-of-the-object" property="name-of-property" />
Bean exampleJava Code:<jsp:useBean id="calendar" scope="page" class="employee.Calendar" /> <h2> Calendar of <jsp:getProperty name="calendar" property="username" /> </h2>
Now you now some basics about the beans tags, its time to show an example:
ConclusionJava 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>
Java server pages are very easy to use and are very productive. They should be used with taglibs and java beans for better results.
Similar Threads
-
Java Server Pages (I)
By Java Tutorial in forum Java TutorialReplies: 0Last Post: 02-17-2008, 11:17 AM -
JSP pages with no caching
By Java Tip in forum Java TipReplies: 0Last Post: 01-31-2008, 12:53 PM -
Getting all the pages from a domain
By eva in forum New To JavaReplies: 0Last Post: 12-25-2007, 11:41 AM -
Help with IRC server in java
By mathias in forum NetworkingReplies: 1Last Post: 08-07-2007, 06:51 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks