dineshonjava

JSP Form Processing

You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your back-end program. The browser uses two methods to pass this information to web server. These methods are GET Method and POST Method.
GET method:
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows:

http://www.dineshonjava.com/hello?key1=value1&key2=value2

The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server.

The GET method has size limitation: only 1024 characters can be in a request string.

This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable which can be handled using getQueryString() and getParameter() methods of request object.

POST method:
A generally more reliable method of passing information to a backend program is the POST method.

This method packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing.

JSP handles this type of requests using getParameter() method to read simple parameters and getInputStream() method to read binary data stream coming from the client.

Reading Form Data using JSP
JSP handles form data parsing automatically using the following methods depending on the situation:


  • getParameter(): You call request.getParameter() method to get the value of a form parameter.
  • getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
  • getParameterNames(): Call this method if you want a complete list of all parameters in the current request.
  • getInputStream(): Call this method to read binary data stream coming from the client.

GET Method Example Using URL:
Here is a simple URL which will pass two values to HelloForm program using GET method.

http://localhost:8080/myapp/index.jsp?first_name=Dinesh&last_name=Rajput

Below is index.jsp JSP program to handle input given by web browser. We are going to use getParameter() method which makes it very easy to access passed information:
<html>
<head>
<title>Using GET Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
   <%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last  Name:</b>
   <%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>

Now open following url-
http://localhost:8080/myapp/index.jsp?first_name=Dinesh&last_name=Rajput


GET Method Example Using Form:
Here is a simple example which passes two values using HTML FORM and submit button. We are going to use same JSP index.jsp to handle this input.
getRequestParam.jsp
<html>
<body>
<form action="index.jsp" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Hit URL:
http://localhost:8080/myapp/getRequestParam.jsp

Try to enter First Name and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example.

http://localhost:8080/myapp/index.jsp?first_name=Dinesh&last_name=Rajput


POST Method Example Using Form:
Let us do little modification in the above JSP to handle GET as well as POST methods. Below is index.jsp JSP program to handle input given by web browser using GET or POST methods.

Infact there is no change in above JSP because only way of passing parameters is changed and no binary data is being passed to the JSP program. File handling related concepts would be explained in separate chapter where we need to read binary data stream.
<html>
<head>
<title>Using GET and POST Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
   <%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last  Name:</b>
   <%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
getRequestParam.jsp
<html>
<body>
<form action="main.jsp" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
http://localhost:8080/myapp/getRequestParam.jsp

Try to enter First Name and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example.

http://localhost:8080/myapp/index.jsp?first_name=Dinesh&last_name=Rajput




<<Previous <<   || Index ||   >>Next >>






JSP Scopes Example

JSP provides very useful features. One of them is maintaining the user defined variable. As you all know that in JAVA, each variable has a scope. Scope decides the accessibility of an object or variable. For example, some variables are accessible within for loop, if-else block or within specific method or class or package.

Same way, in JSP some variables needs to have different scopes than others. JSP provides the capability to user to define the scope of these variables.

Type of Scopes in JSP: 
JSP provides 4 scopes to a variable. Developer can assign any one of them to a variable.

1. Page Scope.
2. Request Scope.
3. Session Scope.
4. Application Scope.
JSP Page Scope Example

Page Scope makes variable available to the developer for the current page only. Once the current page is closed by user or forwarded internally by application or redirected by application, than the variables having page scope will not be accessible on next page.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP Page Scope Example</title>
</head>
<body>
 <c:set var="name" value="Dinesh" scope="page" />
 Local Variable : <c:out value="${name}" />
 <a href="test.jsp">Test Page</a>
</body>
</html> 
Output :
Local Variable: Dinesh
Test Page

Second JSP File(test.jsp):
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
  <title>JSP Page Scope Example</title>
</head>
<body>
 Variable From previous page : <c:out value="${name}" />
</body>
</html>
Output: Variable from previous page:

As you can see above, we created 2 JSPs. On First JSP, we created local variable 'name' using JSTL Core tag c:set. This variable has a value 'Dinesh' and assigned 'Page' scope using scope attribute of c:set tag. We also provided a link on the same JSP that points to another JSP.

When we run the first JSP, it printed variable name successfully and also provided link on the browser.

On Second JSP, we again tried to print the same variable from the first page. So when user click on the link provided on first JSP, it goes to second JSP. However, when second JSP compiled and run, it did not print the variable value defined in first JSP.

This example result of 2 JSPs confirms that, if a variable has Page Scope, it is accessible in only that page and not on any other page.

JSP Request Scope Example

Request Scope makes variable available to the developer for the current request only. Once the current request is over, than the variables having request scope will not be accessible on next request. Single request may include multiple pages using forward.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP Request Scope Example</title>
</head>
<body>
 <c:set var="name" value="Dinesh" scope="request" />
 <jsp:forward page="test.jsp"></jsp:forward>
</body>
</html> 
Second JSP File(test.jsp):
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
  <title>JSP Request Scope Example</title>
</head>
<body>
 Variable From previous page : <c:out value="${name}" />
</body>
</html>
Output: Variable from previous page: Dinesh

As you can see above, we created 2 JSPs. On First JSP, we created local variable 'name' using JSTL Core tag c:set. This variable has a value 'Dinesh' and assigned 'request' scope using scope attribute of c:set tag. We also use jsp:forward tag to forward the same request to another JSP.

When we run the first JSP, it does not print anything on the browser and forwards the request to another JSP. However, it creates a variable before forwarding.

On Second JSP, it prints the variable value defined in first JSP.

This example result of 2 JSPs confirms that, if a variable has Request Scope, it is accessible in current request and on any page as long as request remains same.

JSP Session Scope Example

Session Scope makes variable available to the developer for the current session only. Once the current session is over or timed out, than the variables having session scope will not be accessible on next session.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP Session Scope Example</title>
</head>
<body>
 <c:set var="name" value="Dinesh" scope="session" />
 Local Variable : <c:out value="${name}" />
 <a href="test.jsp">Test Page</a>
</body>
</html> 
Output:
Local Variable: Dinesh
Test Page
Second JSP File(test.jsp):
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
  <title>JSP Session Scope Example</title>
</head>
<body>
 Variable From previous page : <c:out value="${name}" />
</body>
</html>

Output: Variable from previous page: Dinesh

As you can see above, we created 2 JSPs. On First JSP, we created local variable 'name' using JSTL Core tag c:set. This variable has a value 'Dinesh' and assigned 'Session' scope using scope attribute of c:set tag. We also provided a link on the same JSP that points to another JSP.

When we run the first JSP, it printed variable name successfully and also provided link on the browser.

On Second JSP, we again tried to print the same variable from the first page. So when user click on the link provided on first JSP, it goes to second JSP. When second JSP compiled and run, it also printed the variable value defined in first JSP.

This example result of 2 JSPs confirms that, if a variable has Session Scope, it is accessible in only that session. During the current session, variable can be accessed from any JSPs.

JSP Application Scope Example

Application Scope makes variable available to the developer for the full application. It remains available till application is running on server.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP Application Scope Example</title>
</head>
<body>
 <c:set var="name" value="Dinesh" scope="application" />
 Local Variable : <c:out value="${name}" />
 <a href="test.jsp">Test Page</a>
</body>
</html> 
Output:
Local Variable: Dinesh
Test Page

Second JSP File(test.jsp):
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
  <title>JSP Application Scope Example</title>
</head>
<body>
 Variable From previous page : <c:out value="${name}" />
</body>
</html>

Output: Variable from previous page: Dinesh

As you can see above, we created 2 JSPs. On First JSP, we created local variable 'name' using JSTL Core tag c:set. This variable has a value 'Dinesh' and assigned 'Application' scope using scope attribute of c:set tag. We also provided a link on the same JSP that points to another JSP.

When we run the first JSP, it printed variable name successfully and also provided link on the browser.

On Second JSP, we again tried to print the same variable from the first page. So when user click on the link provided on first JSP, it goes to second JSP. When second JSP compiled and run, it also printed the variable value defined in first JSP.

This example result of 2 JSPs confirms that, if a variable has Application Scope, it remains accessible in any JSP during the full application as long as it is running on server.




<<Previous <<   || Index ||   >>Next >>






JSP pageContext Object

JSP pageContext Object is implicitly available to the developer on Java Server Pages. A pageContext implicit object is used for storing and retrieving page-related information and sharing objects within the same translation unit and same request. Also used as a convenience class that maintains a table of all the other implicit objects.

It stores referece to the implicit objects-
The following example shows how PageContext is used to populate other implicit objects.
public void _jspService (HttpServletRequest request, HttpServletResponse response)
    throws java.io.IOException, ServletException { 

     ... 
    try { 

         ... 
        application = pageContext.getServletContext ();
        config = pageContext.getServletConfig ();
        session = pageContext.getSession ();
        out = pageContext.getOut (); 
         ... 

    } catch (Throwable t) {
         ... 
    } finally {
         ... 
    }
}

Provides convenience methods to get and set attributes in different scopes-
This example uses attributes to save and retrieve data in each of the four scopes:
<%
  // Save data
  pageContext.setAttribute("attr1", "value0");  // PAGE_SCOPE is the default
  pageContext.setAttribute("attr2", "value1", PageContext.PAGE_SCOPE);
  pageContext.setAttribute("attr3", "value2", PageContext.REQUEST_SCOPE);
  pageContext.setAttribute("attr4", "value3", PageContext.SESSION_SCOPE);
  pageContext.setAttribute("attr5", "value4", PageContext.APPLICATION_SCOPE);
%>
    
<%-- Show the values --%>
<%= pageContext.getAttribute("attr1") %>
<%= pageContext.getAttribute("attr2", PageContext.PAGE_SCOPE) %>
<%= pageContext.getAttribute("attr3", PageContext.REQUEST_SCOPE) %>
<%= pageContext.getAttribute("attr4", PageContext.SESSION_SCOPE) %>
<%= pageContext.getAttribute("attr5", PageContext.APPLICATION_SCOPE) %>

JSP pageContext Object Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP pageContext Object Example</title>
</head>
<body>
<%  
 JspWriter pw =  pageContext.getOut();
  pw.print("Hello Dinesh....This is another example of JSP 'pageContext' object");
%>
</body>
</html>
As you can see above, using JSP pageContext object, JspWriter instance is created. Using this JspWriter object, String response is set that displayed on the browser when JSP served a request.



<<Previous <<   || Index ||   >>Next >>






page implicit object

The JSP implicit page object is an instance of the java.lang.Object class. It represents the current JSP page. That is, it serves as a reference to the java servlet object that implements the JSP page on which it is accessed. It is not advisable to use this page implicit object often as it consumes large memory.

The page variable is an alias for this, which refers to the servlet instance. It wasn't really very useful when scriptlets were in vogue, and is now completely useless in scriptless pages.

The page implicit object is of type Object and it is assigned a reference to the servlet that executing the _jspService() method. Page is the instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors. Thus in the Servlet generated by tomcat the page object is created as
Object page = this;
Since page is a variable of type Object, it cannot be used to directly call the servlet methods. To access any of the methods of the servlet through page it must be first cast to type Servlet.
<%= this.getServletInfo(); %>
<%= ((Servlet)page).getServletInfo(); %>
But the following code will generate error, because can not use page directly without casting:
<%= page.getServletInfo(); %>



<<Previous <<   || Index ||   >>Next >>






JSP config Object

JSP config Object is implicitly available to the developer on Java Server Pages. Config object is useful in getting application configuration values to JSP from web.xml file. Config object has a scope of application.
following is the list of applicable methods.
  1. getInitParameter ( )
  2. getInitParameterNames()
  3. getServlerName()
JSP config Object Example:

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <display-name>Test</display-name>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 <servlet>
  <servlet-name>ConfigObjectTest</servlet-name>
  <jsp-file>/configTest.jsp</jsp-file>
  <init-param>
   <param-name>name</param-name>
   <param-value>Dinesh</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>ConfigObjectTest</servlet-name>
  <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>

JSP File(configTest.jsp):
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP Application Object Example</title>
</head>
<body>
 Config Value for Parameter 'name' is: <%= config.getInitParameter("name")%>
</body>
</html>

As you can see above, web.xml has a configuration settings for Servlet named as ConfigObjectTest.

This configuration is defined within <servlet> and </servlet> tag.

The name of the servlet is defined within tag <servlet-name> and </servlet-name>

This Servlet specifies the JSP File within <jsp-file> and </jsp-file> tag.

Init Parameter is defined within tag <init-param> and </init-param>

Parameter name is defined within tag <param-name> and </param-name>

Parameter value is defined within tag <param-value> and </param-value>

The Servlet defined above is mapped with Url Pattern. Mapping is done using <servlet-mapping> and </servlet-mapping> tags. Within these tags, servlet is identified using <servlet-name> and </servlet-name>. It must match with the servlet name defined withing <servlet> and </servlet> tag.

Url Pattern is defined within <url-pattern> and <url-pattern> tag.



Once web.xml configuration is completed, the configuration parameters can be accessed in the JSP using config object. Init Parameters can be accessed using getInitParameters method of config object by passing parameter name as an argument.

Other useful methods available to config object are getServletName, getServletcontext and getInitParameterNames.




<<Previous <<   || Index ||   >>Next >>






exception implicit object

The exception object represents all errors and exceptions. The exception implicit object is of type java.langThrowable. You can access the exception object on a page that you declare to be an error page using the isErrorPage attribute of the page directive. Note that the exception object is created only if the JSP uses the page directive to set isErrorPage set to true. When a JSP generates an error and forwards that error to the error page, it sets the JSP exception object of the error page to the generated error
<%@ page isErrorPage='true' %>
Using Exception Object:
The exception object is an instance of a subclass of Throwable (e.g., java.lang. NullPointerException) and is only available in error pages. Following is the list of important methods available in the Throwable class.
public String getMessage():

Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.
public Throwable getCause():

Returns the cause of the exception as represented by a Throwable object.
public void printStackTrace():

Prints the result of toString() along with the stack trace to System.err, the error output stream.
public StackTraceElement [] getStackTrace():

Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.
public Throwable fillInStackTrace():

Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

The following code demonstrates the use of the exception implicit object. The first page uses the errorPage directive to set up the JSP page to use when an error occurs, and the second page called ErrorPage.jsp uses the isErrorPage directive to set itself up to catch the error.

First page
index.jsp

<%@page errorPage="ErrorPage.jsp" %>
<%
String name = null;
int i = 9;
int j = 0;
out.print(i/j);
out.print(name.trim());
%>

ErrorPage.jsp
<%@ page isErrorPage='true' %>
<%
out.print("Error Message : ");  
out.print(exception.getMessage());
%>

There are two kind of errors, compile-time errors and Runtime errors, can occur in the JSP lifecycle:
  1. Compile-time errors : Compile-time errors occur when a client first invokes a JSP. JRun transforms the JSP into its XML view, and then compiles a servlet from the XML view. If an error occurs at any time during this process, a compile-time error is thrown. You must catch that error outside of the JSP. However, if you do not test or precompile the JSP, you might not catch the error at all.
  2. Runtime errors : Runtime errors occur when a JSP successfully compiles but then tries to process code that contains an invalid statement; for example, when you try to include a nonexistent file. Runtime errors are easy to handle because you know that the JSP compiled successfully, you just need to catch the error and examine the output.

JSPs provide robust error-handling capabilities. You can use any Java code error handling techniques, such as try-catch blocks. You can also use the page directive to designate an error page, another JSP that handles the exception.

Example of exception handling in jsp by specifying the error-page element in web.xml file

This approach is better because you don't need to specify the errorPage attribute in each jsp page. Specifying the single entry in the web.xml file will handle the exception. In this case, either specify exception-type or error-code with the location element. If you want to handle all the exception, you will have to specify the java.lang.Exception in the exception-type element. Let's see the simple example:

  • web.xml file for specifying the error-page element
  • index.jsp for input values
  • index.jsp for dividing the two numbers and displaying the result
  • ErrorPage.jsp for displaying the exception
web.xml file if you want to handle any exception
<web-app>

 <error-page>
  <exception-type>java.lang.Exception</exception-type>
  <location>/ErrorPage.jsp</location>
  </error-page>
 
</web-app>
This approach is better if you want to handle any exception. If you know any specific error code and you want to handle that exception, specify the error-code element instead of exception-type as given below:
web.xml file if you want to handle the exception for a specific error code
<web-app>

 <error-page>
  <exception-type>500</exception-type>
  <location>/ErrorPage.jsp</location>
  </error-page>
 
</web-app>


<<Previous <<   || Index ||   >>Next >>






JSP application Object

The application implicit object is an instance of javax.servlet.ServletContext. It is the broadest context state available. It allows the JSP page's servlet and any Web components contained in the same application to share information. A typical use of the application object is to get access to the application wide initialization parameters. The following two scriptlets are equivalent:
<% String path = application.getRealPath ("/WEB-INF/doj.txt"); %>
<% String path = getServletContext ().getRealPath ("/WEB-INF/doj.txt"); %>
Methods of implicit object application:
getAttribute(String name) :

This method returns the 'object' stored in specified attribute name. If the specified parameter does not exist , it will return 'null' value.

Example :
application.getAttribute("doj");
getAttributeNames() :

This method returns all the attributes available within the application. The return type is Enumeration.

Example :
Enumeration doj; 
 doj= application.getAttributeNames();
setAttribute(String objName, Object object) :

This method stores the 'object' in the object name provided(String objname) in the application.

Example :
application.setAttribute("varName", varValue);
removeAttribute(String objName) :

This method is used to remove the specified attribute (String objName) from the application.

Example :
application.setAttribute("password",password);
          application.removeAttribute("password");
getMajorVersion() :

This method is used to return the major version of the Servlet API for the JSP Container.

Example :
out.println("Major Version:"+application.getMajorVersion());
Output : Major Version:2

The above statement gives 2 as the major version of the Servlet API in use for the Application object.

getMinorVersion() :

This method is used to return the minor version of the Servlet API for the JSP Container.

Example :
out.println("Minor Version: "+application.getMinorVersion());
Output : Minor Version: 1

The above statement gives 1 as the minor version of the Servlet API in use for the Application object.

getServerInfo():

The method 'getServerInfo' of Application object is used to return the name and version number of the JRun servlet engine. Information about the JSP Container, such as, the name and product version, are returned by the method getServerInfo of Application object.

Example :
out.println("Server Information:"+application.getServerInfo());
getInitParameter(String name):

The method 'getInitParameter' of Application object is used to return the value of an initialization parameter. If the parameter does not exist, then null value is returned.

Example :
String doj = application.getInitParameter("eURL");
In the above example, the value of initialization parameter "eURL" is retrieved and stored in string "doj".

getInitParameterNames() :

The method 'getInitParameterNames' of Application object is used to return the name of all initialization parameter of the application. The returned value is an enumeration.

Example :
Enumeration e;
 e=application.getInitParameterNames();
getResourceAsStream(Path):

The method 'getResourceAsStream' of Application object is used to translate the resource URL mentioned as parameter in the method , into an input stream to read.
Example :
InputStream stream = application.getResourceAsStream("/doj.txt")
log(Message) :

The method log of Application object is used to write a text string to the JSP Container?s default log file. General syntax of log method of Application object is as follows :
application.log(Message);

JSP application Object Example:

First JSP:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP Application Object Example</title>
</head>
<body>
 <% 
  application.setAttribute("name", "Dinesh");
 %>
 <a href="test.jsp?id=5">JSP Application Example</a>
</body>
</html>

Second JSP:
test.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP Application Object Example</title>
</head>
<body>
 Application attribute value: <%=application.getAttribute("name")%>
</body>
</html>




<<Previous <<   || Index ||   >>Next >>






JSP session Object

JSP session Object is implicitly available to the developer on Java Server Pages. Session object is useful in maintaining objects and accessing it values in different JSPs. Session object has a scope of session.

Session Object represents the data associated with a user's session. The request and response, are used to pass information from web browser to server and from server to web browser respectively. While the connection between client & the server is provided by "session" object. The main use of 'session' object is to maintain states during multiple page requests.

The main feature of session object is to navigate between multiple pages in a application where variables are stored for the entire user session. The session objects do not lose the variables and the value remains for the user?s session. The concept of maintenance of sessions can be performed by cookies or URL rewriting.

Methods of session object:
setAttribute(String, object) :

his method sets the value of object as string's value and you can get this value in other JSP page which is connected to this page.

getAttribute(String name) :

This method is use to fetch the value of "String" which is set by you, in other JSP page, using "setAttribute()" method.

getAttributeNames() :

The "getAttributeNames" method of session object is used to retrieve all attribute names associated with the current session. The name of each object of the current session is returned. The value returned by this method is an enumeration of objects that contains all the unique names stored in the session object.

isNew():

The isNew() method of session object returns a true value if the session is new. If the session is not new, then a false value is returned. The session is marked as new if the server has created the session, but the client has not yet acknowledged the session. If a client has not yet chosen the session, i.e., the client switched off the cookie by choice, then the session is considered new. Then the isNew() method returns true value until the client joins the session. Thus, the isNew() method session object returns a Boolean value of true of false.

invalidate():

This method invalidates this session and unbinds any objects bound to it.
Check whether session object is null or not. If the session object null means, session is already expired or not yet initiated. Use invalidate() method on session object to invalidate a session if the session object is not null.

setMaxInactiveInterval(int interval):

Get max time in milliseconds of inactive interval. This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

getMaxInactiveInterval():

This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.

removeAttribute(String name):

Remove attribute of given name from session object.

public long getLastAccessedTime():

This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.

public String getId():

This method returns a string containing the unique identifier assigned to this session.



<<Previous <<   || Index ||   >>Next >>






JSP out Object

JSP out Object is implicitly available to the developer on Java Server Pages. Out object denotes the Output stream in the context of page. The class or the interface name of the object out is "jsp.JspWriter". This object is instantiated implicitly from JSP Writer class and can be used for displaying anything within delimiters.
Methods in out object
  • print
  • println
  • newLine
  • clear
  • clearBuffer
  • flush
  • isAutoFlush
  • getBufferSize
  • getRemaining.
print() :

The print method of out object writes the value to the output without a newline character.
Example :
If a JSP program has the following statements :
out.print("Welcome!!!"); 
  out.print("To dineshonjava.com");
Output :

Welcome!!! dineshonjava.com

println() :

The println method of out object writes the value to the output with a newline character.
out.println("Welcome!!!"); 
  out.println("Dinesh");
Output :
Welcome!!!
Dinesh
newLine :

The 'newLine' method of out object is used to write a newline character to the output.
Example : If a JSP program has the following statements :
out.write("Welcome!!!");
out.newLine();
out.write("Dinesh");
Output :
Welcome!!!
Dinesh
clear :

The clear method of out object is used to clear the output buffer. This method does not write any contents to the client. An exception is thrown by this method if the buffer was flushed.
Syntax : out.clear() ;
clearBuffer :

The 'clearBuffer' method of out object is used to clear the output buffer. This method does not write any contents to the client. The only difference between the 'clear' method of out object and 'clearBuffer' method is 'clear' method throws an exception when the buffer is flushed. 'clearBuffer' method does not throw an exception when the buffer is flushed.
Example :
if (out.getBufferSize() != 0)
                out.clearBuffer();
flush :

Two methods of out object, 'clear' and 'clearBuffer' are used to clear the output buffer without writing any contents to the client. The 'flush' method of out object is used to flush the buffer by writing the contents to the client.
Example :
out.flush(); 
 <jsp:forward page="hello.jsp"/>
In the above example, no forwarding will take place. This is because of the "out.flush()" method. This method will flush the "JspWriter" buffer. Once the content is written to the browser, a forward cannot be invoked.

isAutoFlush() :

The "isAutoFlush" method of 'out' object returns a 'true' value if the output buffer is automatically flushed otherwise returns 'false'.
Syntax: out.isAutoFlush() ;
getBufferSize :

The "getBufferSize" method of 'out' object is used to return the size of the buffer. The returned value of the size of the buffer is in bytes. If the output is not buffered, then the "getBufferSize" method returns a 0 byte.
Example :
if (out.getBufferSize() != 0)
    out.getBufferSize()
getRemaining() :

The "getRemaining" method of out object is used to return the number of empty bytes in the buffer.
Syntax : out.getRemaining() ;

JSP out Object Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP pageContext Object Example</title>
</head>
<body>
<%  
 out.println("Hello Dinesh!!!!!!");
%>
</body>
</html>

Output on browser: Hello Dinesh!!!!!!

As you can see above, using JSP out object, String response is displayed on the browser when JSP served a request.

Copy implicitobjects folder on webapp directory of tomcat at
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\

and restart server and hit the following URL
http://localhost:8080/implicitobjects/index.jsp



Download Example.


<<Previous <<   || Index ||   >>Next >>






JSP Response Object

JSP Response Object is implicitly available to the developer on Java Server Pages. This object implements javax.servlet.ServletResponse interface. It is useful object in setting response to serve the request. This object has a scope for that specific request. "HttpServletResponse" class and using this object, response parameters can be modified or set. The response object handles the output of the client. The response object is generally used by cookies. The response object is also used with HTTP Headers.
Methods of response object
  • setContentType()
  • addCookie(Cookie cookie)
  • addHeader(String name, String value)
  • containsHeader(String name)
  • setHeader(String name, String value)
  • sendRedirect(String)
  • sendError(int status_code)
setContentType():

The "setContentType()" method of response object is used to set the MIME type and character encoding for the page.
Example :
response.setContentType("text/html");

addCookie(Cookie cookie):

This method is used to add the specified cookie to the response . If you wants to add more than one cookie, then use this method by calling it as many times as required.
Example :
response.addCookie(Cookie dineshonjava) ;

addHeader(String name, String value):

This method is used to write the header to the response as pair of name and value. If the header is already present, then value is added to the existing header values. General syntax of addHeader() of response object is as follows:
response.addHeader(String name, String value)
Example :
response.addHeader("User", "Dinesh") ;

containsHeader(String name):

The "containsHeader()" method of response object is used to check whether the header, given as parameter, already included to the response or not. If the named response header is set then it returns a true value. If the named response header is not set, the value is returned as false.
Example :
response.containsHeader(String Author)

setHeader(String name, String value):

This method is used to write the header to the response as pair of name and value a string. If the header is already present, then the original value is replaced by the current value given as parameter in this method. General syntax of "setHeader" of response object is as follows
response.setHeader(String name, String value)
Example:
response.setHeader("Content_Type","text/html");

sendRedirect(String):

This method is used to send a response which redirect client to new page. But one must note that if the JSP, in execution, has already sent page content to the client, then the "sendRedirect()" method of response object will not work and will fail. General syntax of sendRedirect of response object is as follows:
response.sendRedirect(String)
Example :
response.sendRedirect("http://www.dineshonjava.com/") ;

sendError(int status_code , java.lang.String msg) :

Sends an error response to the client using the specified status code and descriptive message. If the response has already been committed, this method throws an "IllegalStateException". After using this method, the response should be considered to be committed and should not be written to.

JSP Response Object Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.io.PrintWriter"%>
<html>
<head>
<title>JSP Request Object Example</title>
</head>
<body>
<%  
 PrintWriter pw =  response.getWriter();
  pw.print("Hello Dinesh....This is an example of JSP 'Response' object");
%>
</body>
</html>

Output on Browser: Hello Dinesh....This is example of JSP 'Response' object

As you can see above, using JSP response object, PrintWriter instance is created. Using this PrintWriter object, String response is set that displayed on the browser when JSP served a request.

Copy implicitobjects folder on webapp directory of tomcat at
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\

and restart server and hit the following URL
http://localhost:8080/implicitobjects/index.jsp



Download Example.


<<Previous <<   || Index ||   >>Next >>






JSP Request Object

JSP Request Object is implicitly available to the developer on Java Server Pages. This object implements javax.servlet.ServletRequest interface. It is useful object in getting request parameters. This object has a scope for that specific request.

This object retrieves values whatever client passes to the server by an HTTP request. Let if you submit the html form with some data to be send to the server, is received by the HTTP request object of the JSP. To access the HTML form data we use the request object and it's several methods like getParameter().

All the things like headers, cookies or parameters are sent from the client browser to the server during an HTTP request object which most common use of the request object is to obtain parameter or query string values. you can illustrates more about the request object for parsing form data by using the following program when you will direct copy and paste this in your JSP application.

Methods of the request object is explained one by one as follows:
request.getParameter(String name):

This is the method, used for getting the value of the HTML form attribute. This method returns the string type value i.e. the value of the specified field of an HTML form. This method takes a string type parameter which is the name of the attribute of the html which value has to be retrieved through the request object.
request.getParameterNames():

This is the method of the request object used for getting the enumeration of the attributes of the html form. These values are later retrieved through the java programming language by enumerating the retrieved enumerated data by the method of the request object.
request.getParameterValues(String name):

This is the method of the request object used for getting the string array containing all of the values which are contained by the request parameter. This method takes a String type parameter which is the name of the field of the html form. This method is used where the array of controls of the HTML lies. All the control of the HTML form contains same name and then makes a control array.
request.getCookies():

This is the method of the request object used for getting all the cookies existed in the HTTP request object.
request.getQueryString():

This is the method of the request object used for getting the query string which is the values with the attribute of the html from where the jsp page is referenced.
request.getRequestURI():

This is the method of the request object used for getting the URI of the current page.
request.getHeaderNames():

This method returns the enumerator of all HTTP header names means this method retrieves name of all the headers in enumeration form that is enumerated and get all the name one by one by using the Enumeration.nextElement() up to the last element of the enumeration.
request.getHeader(String hdr):

This is the method return the value of the HTTP header like query string or the URL. This method takes a string parameter which is the header name retrieved by the method getHeaderNames() of the request object that gives all the HTTP header names in the enumeration form which has to be converted into string form later for getting the value of the value of the HTTP header from if one by one.
request.getAttribute(String):

This method is used for getting the value of the attribute which is set through the setAttribute(String attributeName) method of the request object. This method takes a string type parameter written in double quotes ("") i.e. the attribute name that is specified in the page where the value of the attribute is set with the attribute name is to be retrieved either in the current page or any other page by passing the value the attribute name through the request object by using dispatcher method.
request.getAttributeNames():

Above method is used for retrieving all the attributes name in the current session of the page. This method returns the enumerated data which is to be retrieved later by enumerating.
request.setAttribute(String, object):

Above method sets the value of the attribute for the request which is retrieved later either in the current JSP page or the another JSP page by passing the request object through the dispatcher method. The set value of the attribute is retrieved by the getAttribute(String) method of the request object.
request.removeAttribute(String):

This method removes the attribute. This method takes a string type parameter i.e. the attribute name that has to be removed. After applying this method you can't access the attribute. If you specify the method for getting the value of the attribute what has removed, you will get the null value.

JSP Request Object Example:

First JSP (index.jsp)
<html>
<head><title>Implicit Request Object In JSP.</title></head>
  <body>
   <form action="getRequestParam.jsp" method="post">
 <table border="1">
   <tr>
  <td>User Name: </td>
  <td><input type="text" size="20" name="userName" />
   </tr>
   <tr>
  <td>Password: </td>
  <td><input type="password" size="20" name="password" />
   </tr>
   <tr>
         <td>&nbsp;</td>
  <td><input type="submit" value="Submit"/></td>
   </tr>
 </table>
   </form>
  </body>
</html>

Second JSP (getRequestParam.jsp):
<%@page import="java.util.*" %>
<%
 String username;
 String password;
 if(request.getParameter("userName") == null)
  username = "";
 else
  username = request.getParameter("userName");
 
 if(request.getParameter("password") == null)
  password = "";
 else
  password = request.getParameter("password");
%>
<table align="center" bgcolor="pink" border="1">
 <tr>
  <td align><b>Your User Name: </b></td>
  <td><%=username %><br/></td>
 </tr>
 <tr>
  <td><b>Your Password: </b></td>
  <td><%=password %></td>
 </tr>
</table>

Copy implicitobjects folder on webapp directory of tomcat at
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\

and restart server and hit the following URL
http://localhost:8080/implicitobjects/index.jsp


As you can see above, First JSP has two fields "userName" and "password" have one submit button that points to another JSP getRequestParam.jsp. With that button, parameter "userName" and "password" are sent second jsp.

This parameter is read on Second JSP with the help of getParameter() method of HttpServletRequest object "request". With the help of scriptlet, request object printed the value of parameter "userName" and "password" on browser.

As you have noticed here, request object is implicit and there is no need to define it on JSP. You can call these objects directly with the name of implicit object.

Fill user name and password and submit then forward to second jsp as following url.
http://localhost:8080/implicitobjects/getRequestParam.jsp


Download Example.


<<Previous <<   || Index ||   >>Next >>






JSP Implicit Objects

JSP Container makes certain JAVA Objects available on JSP. These objects are called Implicit objects. 

JSP Implicit objects are created by the web container. Implicit objects need not to be declared, defined or instantiated like other JAVA Objects. These implicit objects are Java objects that implement interfaces in the Servlet and JSP API. Scripting elements in a JSP page can make use of these JSP implicit objects. There are nine JSP implicit objects available.

Developer can use these objects by directly calling it by name.

1 request implicit object :

This is the HttpServletRequest associated with the request, and lets you look at the request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies, Referer, etc.).

Strictly speaking, request is allowed to be a subclass of ServletRequest other than HttpServletRequest, if the protocol in the request is something other than HTTP.
2 response implicit object :

The JSP implicit response object is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. It represents the response to be given to the client. The response implicit object is generally used to set the response content type, add cookie and redirect the response.Container generates to this object and passes to the _jspService() method as a parameter.

Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client.

3 out implicit object :

This is the PrintWriter used to send output to the client.

However, in order to make the response object (see the previous section) useful, this is a buffered version of PrintWriter called JspWriter.

Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive.

Also note that out is used almost exclusively in scriptlets, since JSP expressions automatically get placed in the output stream, and thus rarely need to refer to out explicitly.
4 session implicit object :

This is the HttpSession object associated with the request.

Recall that sessions are created automatically, so this variable is bound even if there was no incoming session reference.

The one exception is if you use the session attribute of the page directive to turn sessions off, in which case attempts to reference the session variable cause errors at the time the JSP page is translated into a servlet.
5 application implicit object :

This is the ServletContext as obtained via getServletConfig().getContext(). It is used to share information among all users of a currently active application. The JSP implicit application object is an instance of a java class that implements the javax.servlet.ServletContext interface. It gives facility for a JSP page to obtain and set information about the web application in which it is running.
6 exception implicit object :

The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It represents the occurred exception that caused the control to pass to the JSP error page.
7 config implicit object :

The JSP implicit config object is an instance of the java class that implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the initialization parameters available.
8 page implicit object :

The JSP implicit page object is an instance of the java.lang.Object class. It represents the current JSP page. That is, it serves as a reference to the java servlet object that implements the JSP page on which it is accessed. It is not advisable to use this page implicit object often as it consumes large memory.
9 pageContext implicit object :

JSP introduced a new class called PageContext to encapsulate use of server-specific features like higher performance JspWriters.

The idea is that, if you access them through this class rather than directly, your code will still run on "regular" servlet/JSP engines.




<<Previous <<   || Index ||   >>Next >>






GetProperty Tag in JSP

The getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.

The getProperty action has only two attributes, both of which are required ans simple syntax is as follows:
<jsp:useBean id="myName" ... />
...
<jsp:getProperty name="myName" property="someProperty" .../>
Explanation: As shown above, getProperty tag in JSP has two attributes "name" and "property". Please note that jsp:getProperty tag must be used with jsp:useBean tag.
  • name Attribute: name attribute in JSP getProperty tag must match with useBean Tag. If JSP has multiple useBean tag, id of the useBean tag is used to identify the bean. While getting property of that bean, id in useBean tag must match with name attribute in getProperty Tag.
  • property Attribute: property attribute in JSP getProperty Tag idnetifies the property whose value is being requested by this tag.
Example-
Employee.java
package com.dineshonjava.bean;

/**
 * @author Dinesh Rajput
 *
 */
public class Employee {
 private String firstName;
 private String lastName;
 private String address;
 
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 
}
index.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<html>
 <body>
  <h1>Employee Form Bean Value</h1>
    <jsp:useBean id="emp" class="com.dineshonjava.bean.Employee" scope="page" />
        
    <jsp:setProperty name="emp" property="firstName" value="Dinesh"/>
    <jsp:setProperty name="emp" property="lastName" value="Rajput"/>
    <jsp:setProperty name="emp" property="address" value="Noida"/>
        
     <table>
      <tr>
       <td>First Name</td>
       <td> : </td>
       <td> <jsp:getProperty name="emp" property="firstName"/> </td>
      </tr>
      <tr>
       <td>Last Name</td>
       <td> : </td>
       <td> <jsp:getProperty name="emp" property="lastName"/> </td>
      </tr>
      <tr>
       <td>Address</td>
       <td> : </td>
       <td> <jsp:getProperty name="emp" property="address"/> </td>
      </tr>
     </table>
        
  </body>
</html>

Copy myapp folder on webapp directory of tomcat at
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\

and restart server and hit the following URL
http://localhost:8080/myapp/index.jsp




Download Example


<<Previous <<   || Index ||   >>Next >>






SetProperty Tag in JSP

In this Tutorial we want to describe you a code that help in describing an example from JSP bean set property. 

SetProperty tag in JSP is used to set properties of the JAVA bean.

General syntex of JSP setProperty Tag look like this:
Syntax:
<jsp:setProperty name="xyz" property="xyz" value="xyz"/>
The code include a package bean , we have a class Employees. The employee class include a string variable first name, last name and address. Inside the class we have a setter and getter method.
1. set XXX ( ): This method hold the value of the parameter by the implementor of interface.
2. get XXX( ): This method retrieve the value of the parameter set in the setXXX () method.
The JSP page uses this getter and setter method.

<jsp:useBean> -
1. The < jsp:use Bean> instantiate a bean class and locate a bean class with specific scope and name.
  • id - A id variable is used to identify the bean in the scope .
  • class -The class is represented as Package. class and instantiate a bean from class. The class should be public
  • scope -This describe you the scope of the bean in which it exists.
2. <jsp:set Property> This is used to set the value of one or more properties of bean using setter method. The value of the name must match with the Id.
3. <jsp:get Property> This is used to return the bean property value using property getter method in bean package.

Example-
Employee.java
package com.dineshonjava.bean;

/**
 * @author Dinesh Rajput
 *
 */
public class Employee {
 private String firstName;
 private String lastName;
 private String address;
 
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getAddress() {
  return address;
 }
 public void setAddress(String address) {
  this.address = address;
 }
 
}

index.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<html>
 <body>
  <h1>Employee Form Bean Value</h1>
    <jsp:useBean id="emp" class="com.dineshonjava.bean.Employee" scope="page" />
        
    <jsp:setProperty name="emp" property="firstName" value="Dinesh"/>
    <jsp:setProperty name="emp" property="lastName" value="Rajput"/>
    <jsp:setProperty name="emp" property="address" value="Noida"/>
        
     <table>
      <tr>
       <td>First Name</td>
       <td> : </td>
       <td> <jsp:getProperty name="emp" property="firstName"/> </td>
      </tr>
      <tr>
       <td>Last Name</td>
       <td> : </td>
       <td> <jsp:getProperty name="emp" property="lastName"/> </td>
      </tr>
      <tr>
       <td>Address</td>
       <td> : </td>
       <td> <jsp:getProperty name="emp" property="address"/> </td>
      </tr>
     </table>
        
  </body>
</html>

Copy myapp folder on webapp directory of tomcat at
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\

and restart server and hit the following URL
http://localhost:8080/myapp/index.jsp



Download Example



<<Previous <<   || Index ||   >>Next >>