32 JSP – II

Dr S. Abirami

1. JSPElements – JSP Actions

 

Let us explore the JSP Action elements first. Actions are high-level JSP elements which are used to create, modify or use other JSP objects. Unlike directives and scripting elements, JSP actions are coded using strict XML syntax form. By using of JSP action elements we can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugins etc.Usage of syntax for the Action element, is given below as it conforms to the XML standard:

 

<jsp:action_name attribute=”value” />

Action elements are basically predefined functions and the following JSP actions are available for use:

<jsp:param>,   <jsp:include>,    <jsp:forward>,    <jsp:fallback>,    <jsp:plugin>,    <jsp:useBean>,

<jsp:setProperty>,         <jsp:getProperty>

Let us explore the element tags one by one,

 

1.1 JSP Elements: JSP Actions (param)

 

The <jsp:param> action is basically used to provide information in the form of name value pairs to the current request. This action can also be used in alongwith jsp:include, jsp:forward andjsp:pluginactions. The syntax of jsp:param is

 

<jsp:param name=”parameter_name” value=”parameter_value” />

 

Example for jsp:param tag is:

 

<jsp: include page “process.jsp”> <jsp:param name = “user” value = “mona”/> <jsp:param name = “sessionid” value = “1234D3F”/>

</jsp:include>

 

1.2 JSP Elements: JSP Actions (include)

 

The jsp:include action tag is used to include the content of other resources such as a jsp, html or servlet file in a JSP page. The jsp:include tag can also be used to include static as well as dynamic pages. The jsp include action tag tries to include the resources at the request time and it is a good opinion for dynamic pages. The advantage of jsp: include is code reusability where we can make of use a page number of times.For example we can use jsp include action tag for including header and footer pages in all the pages. This may save a lots of time.

 

Syntax of jsp:include action tag without parameter is:

<jsp:include page=”relativeURL | <%= expression %>” />

Syntax of jsp:include action tag with parameter is:

<jsp:include page=”relativeURL | <%= expression %>”>

<jsp:param name=”parametername” value=”parametervalue | <%=expression%>” /> </jsp:include>

 

An example of jsp:include action tag without parameter is given below.In this example, index.jsp file includes the content of the printdate.jsp file.

 

File: index.jsp

 

<h2>this is index page</h2>

<jsp:include page=”printdate.jsp” />

<h2>end section of index page</h2> File: printdate.jsp

<% out.print (“Today is:”+java.util.Calendar.getInstance ().getTime ()); %>

Now the difference betweenjsp:include and include directive used in JSPshould be known. This is explained in Table 1.

 

Table 1. Comparison between jsp:include and include directive

 

 

1.3 JSP Elements: JSP Actions (forward)

 

While we use forward action tag , the current page stops processing the request and forwards the request to another page. After execution forwarding to the new page, execution never returns to the calling or current page.

 

Syntax of JSP Action(forward) tag is :

<jsp:forward page= “file_name” />

Or it can be also be written as:

<jsp: forward page= “file_name”>

<jsp:param name=”parameter_name” value=”parameter_value” /></jsp: forward>

 

An example of jsp:forward action tag without parameter is discussed here.In the following example, an attempt has been made to simply forward the request to the print date .jsp file.

 

index.jsp

 

<html>

<body>

<h2>this is index page</h2>

<jsp:forward page=”printdate.jsp” />

</body>

</html>

 

1.4JSP Elements: JSP Actions (useBean)

 

Usage of beantag through JSP actions instantiates a Java bean object into the JSP page. (UseBeanProperty has been used in two flavors: getProperty and setProperty. jsp:useBean creates a new instance of a bean and its syntax is

 

<jsp:useBean id=“object_Name” class=“class name“ >

 

Where id is the name of the object, class is aJavabean class from which the object gets instantiated.

 

This is equivalent to the JSP systax:

<% class_name object_name = new class_name(); %>

 

Example to instantiate a Factorial bean in a JSP page is given below:

<jsp:useBean id = “fact” class = “bean.Factorial”/>

 

This is equivalent to the JSP scriplet

<% bean.Factorial fact = new bean.Factorial(); %>

   

1.4.1 JSP Actions (jsp:setProperty)

 

jsp:getProperty reads and outputs the value of a bean property (ie.,calling a getter method) and its syntax is

 

<jsp:getProperty name=”beanName” property=”propertyName” />

An example for gtPropertyis <jsp:getProperty name = “fact” property = “value”/>

This is equivalent to JSP Scriplet:

<%= fact.getValue() %>

 

1.4.2 JSP Actions (jsp:setProperty)

 

jsp:setProperty modifies a bean property (by calling a setter method)

 

<jsp:setProperty

name=”beanName”

property=”propertyName“

value=”propertyValue” />

An example for Set Property is:

<jsp: setProperty name=“fact” property = “value” value =“5” />

This is equivalent to the JSP Scriplet:

<%fact.setValue(5)%>

 

2.JSP Implicit Objects

 

JSP implicit objects are created by the container automatically. When a web server processes a JSP page( during the translation of a JSP page to a Servlet source to help developers). These objects can also be used directly in scriptlets that goes in service method. Nine Implicit Objects can be used in a JSP page as discussed below:

    a) Request object: Request implicit object is to get the data on a JSP page which has been entered by the user in frontend

String Uid= request.getParameter(“user-id”);

String Pass= request.getParameter(“password”);

 

b) Response Object: This is the HttpServletResponse object associated with the response to the client this is used to send responses to the client.

 

response.setContentType(“text/html”);

response.setContentType(“image/gif”);

response.setContentType(“image/png”);

response.setContentType(“application/pdf”);

 

c) Session:This is the most frequently used implicit object, which is used for storing the user’s data to make    it available on other JSP pages till the user     session is active.

 

d) Out: This is used for writing content to the client(browser). This has several methods which can be used for properly formatting output message to the browser and for dealing with the buffer.

 

Example:

 

out.println(“hi”); out.println(“hello”);

 

e) Application:This is used for getting application-wide initialization parameters and to maintain useful data across whole JSP application.

 

Example:

 

String s = (String)application.getAttribute(“MyAttr”);

 

This example would return the object stored in the attribute “MyAttr”.

 

f) Exception:This object is used in exception handling for displaying error messages. This object is only available to the JSP pages, whereisErrorPage attribute is set to true.

 

g) Page : JSP page implicit object is an instance of java.lang.Object class, which indicates the current JSP page. The Page object provide reference to the generated servlet class.

 

h) PageContext Object : This implicit object is an instance of javax.servlet.jsp.PageContextabstract classimplementation. PageContext to get and set attributes with different scopes and to forward request to other resources. PageContext objectccan be used also holds references to other implicit objects.

 

i) Config Object : This is used to get the JSP initparamsconfigured in the deployment descriptor.

     

2.1 JSP Implicit objects – Class files (instantiation)

 

The JSP Class files which are involved in Implicit objects are defined below:

 

•  application: javax.servlet.ServletContext

•  config: javax.servlet.ServletConfig

•  exception: java.lang.Throwable

•  out: javax.servlet.jsp.JspWriter

•  page: java.lang.Object

•  pageContext: javax.servlet.jsp.PageContext

•  request: javax.servlet.ServletRequest

•  response: javax.servlet.ServletResponse

•  session: javax.servlet.http.HttpSession

 

2.2 Example for the JSP Implicit objects

 

To demonstrate the usage of JSP Implicit objects, an example which makes use of Request, Response, Out and session objects has been given below,

 

Index.html

 

<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>

 

Sign in Form: Receiving id and password from User Login page

 

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(“Chaitanya”) &&password.equals(“BeginnersBook”))

{ response.sendRedirect(“success.jsp”); }

else { response.sendRedirect(“failed.jsp”); } %> </body>

</html>

 

This JSP page verifies the input id/pass against hard-coded values.

   success.jsp

 

<html>

<head>

<title>Success Page</title>

</head>

<body>

<% String data=(String)session.getAttribute (“session-uid”); out.println(“Welcome “+ data+”!!”); %>

</body>

</html>

 

This JSP page would execute if id/pass are matched to the hardcoded userid/password.

 

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>

 

The control will be redirected to this page if the credentials entered by user are wrong.

Output of JSP page thatreceives id and password andcorrectlyverified is shown in Figure 1.

 

Figure 1Output of JSP page that receive id and password andcorrect verification.

 

If Sign-In has been failed ,when Id and Password provided is are wrong the output is displayed shown in Figure2.

 

    3.JSP – Exception Handling

 

The exception is normally an object that is thrown during the runtime. Exception Handling is the processused to handle the runtime errors. There may be a possibility that exception may occur at any time in our web application. So handling exceptions is a safer side for the web developers.

 

In JSP, there are two ways to perform exception handling, one is by using errorPage and isErrorPage attributes of page directive and the other one is by using<error-page> element in web.xml file.

 

3.1 Example of JSPexception handling using the elements of page directive

 

To demonstrate the usage of JSP Exception Handling, three jsp pages have been designed in this example. Out of which, one page has been defined/created to handle the exceptions(in this example names error.jsp). Another page is defined with errorPage attribute of page directive.(as defined by the process.jsp page) and one more page is used for getting values.

 

Define and create a page to handle the exceptions, named error.jsp page, where the possibility of exception may arise, For example : 3 files are designed

  • index.jsp for getting input values
  • process.jsp for dividing the two numbers and displaying the result
  • error.jsp for handling the exception

      index.jsp

 

<form action=”process.jsp”>

No1:<input type=”text” name=”n1″ /><br/><br/> No1:<input type=”text” name=”n2″ /><br/><br/> <input type=”submit” value=”divide”/> </form>

 

process.jsp

 

<%@ page errorPage=”error.jsp” %>

<%

String num1=request.getParameter(“n1”);

String num2=request.getParameter(“n2”);

int a=Integer.parseInt(num1);

int b=Integer.parseInt(num2);

int c=a/b;

out.print(“division of numbers is: “+c);

%>

 

error.jsp

   <%@ page isErrorPage=”true” %>

<h3>Sorry an exception occured!</h3>

Exception is: <%= exception %>

Output of this example is given in Figure 3 and Figure 4.

 

 

5.  JSP Session Tracking

 

In a web application, server may be responding to several clients at a time. Hence, so session tracking is a way by which a server can identify the client uniquely.As we know HTTP protocol is stateless which means client needs to open a separate connection every time it interacts with server and server treats each request as a new request. In order to identify the client, server needs to maintain the state and to do so, there are several session tracking techniques. They are listed below:

   

5.1 Session Tracking Techniques

 

Session Tracking has following fields:

 

• Hidden fields

• URL rewriting

• Cookies

• Session Objects

 

With Cookies, Hidden Fields and URL rewriting approaches, client always sends a unique identifier with each request and server determines the user session based on that unique identifier whereas in the session tracking approach using Session Object it uses all the other three techniques internally.

 

5.2 Session tracking using Cookies:

 

Out of the four session tracking techniques, session tracking using cookie has been discussed here, If cookie is associated with the client request, server will associate it with corresponding user session otherwise it will create a new unique cookie and send it back with response. Cookie objects are can be created using a name value pair.For example we can create a cookie with the name sessionId and with a unique value for each client. Later this can be added it in a response so that it will be sent back to the client.

 

Syntax of creating Cookie in a JSP is:

 

Cookie cookie = new Cookie(“sessionID”, “some unique value”); response.addCookie(cookie);

 

The following examples illustrate the usage of cookie1.jsp is used to accept the username. Cookie2.jsp creates and sets a cookie with maximum age, whereas cookie3.jsp file is used to display the values of the cookies.

 

cookie1.jsp:

 

<html>

<body>

<form method = “post” action=”cookie2.jsp”> <font>Username<input type = “text” name = “name”></font> </font><br>

<input type = “submit” name = “submit” value = “submit” >

</form>

</body>

</html>

   

cookie2.jsp:

 

<%@ page language=”java” import=”java.util.*”%> <% String name=request.getParameter(“name”); Cookie cookie = new Cookie (“name”,name); response.addCookie(cookie); cookie.setMaxAge(50 * 50); //Time is in Minutes%>

<a href=”cookie3.jsp”>Continue</a>

cookie3.jsp:

<p>Display the value of the Cookie</p>

<%

Cookie[] cookies = request.getCookies();

for (inti=0; i<cookies.length; i++)

{

if(cookies[i].getName().equals(“name”))

out.println(“Hello”+cookies[i].getValue());

}

%>

With respect to the above code, output of Cookie1.jsp, Cookie2.jsp and Cookie3.jsp has been shown in the figures 5, 6, 7 respectively.

 

Figure 4. Output of Cookie1.jsp

   Summary

 

This Chapter illustrated the usage of JSP action tags with its various types and formats.This Chapter has also demonstrated the usage of various implicit objects with suitable examples. Later the usage of cookies in session tracking has also been dealt.

 

Web Links