Tuesday, October 27, 2015

Java Server Pages ( JSP )

 
 
 
JavaServer Pages, or JSP, is a server-side programming technology that we can use to create of dynamic web pages.
 
When using JSP we can access the entire Java APIs, including the JDBC API to access databases.

JavaServer Pages can render web pages with dynamic content.
We can use Java code in HTML pages by making use of special JSP tags, <% %>.

A JavaServer Pages are a type of Java servlet that is designed to create user interface for a Java web application.

We create JSP pages in text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.

In JavaServer Pages, we can get user input through web forms(<form> tag), present records from a database, and create web pages dynamically.

When using JSP we create our own custom tags or use the existing tag library. A JSP tag looks like a normal HTML tag.

Setting up Java Development Kit

First, download Java Software Development Kit (JDK) from Oracle's Java site and setting up PATH environment variable appropriately.

Install and configure the JDK and set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

For example,
set PATH=C:\jdk1.8\bin;%PATH%
set JAVA_HOME=C:\jdk1.8

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.8 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.8/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.8

Setting up Web Server: Tomcat

Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies.  Download latest version of Tomcat from http://tomcat.apache.org/.
Unpack the binary distribution.

Tomcat can be started by executing the following commands on windows machine:
C:\apache-tomcat-8\bin\startup.bat

After a successful startup, the default web applications will be available by visiting http://localhost:8080/.

Tomcat can be stopped by executing the following commands on windows machine:
C:\apache-tomcat-8\bin\shutdown

JSP Life Cycle

A JSP life cycle are listed as follows.
  • Compilation
  • Initialization
  • Execution
  • Cleanup
When a browser requests a JSP from the JSP engine, the JSP engine first checks to see whether it needs to compile the page.

If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.

Example

Suppose your Apache Tomcat is installed in C:\apache-tomcat.
Save the code below in JSP file hello.jsp and put this file in C:\apache-tomcat\webapps\ROOT directory and try to browse it by giving URL http://localhost:8080/hello.jsp  in your browser address bar.

<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>


Date Formatting using SimpleDateFormat

SimpleDateFormat can format and parse dates in a locale-sensitive manner.
The following code shows how to output current time.

<%@ page import="java.io.*,java.util.*" %>
<%@ page import="javax.servlet.*,java.text.*" %>
<html>
<body>
<%
   Date dNow = new Date();
   SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
   out.print( "<h2 align=\"center\">" + ft.format(dNow) + "</h2>");
%>
</body>
</html>


Scriptlet

A JSP scriptlet can contain Java language statements, variable or method declarations, or expressions that are valid in the page scripting language.

We can use the following syntax to include Scriptlet in JSP.
<% code fragment %>

For example,

<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

You can write XML equivalent of the above syntax as follows:

<jsp:scriptlet>
   code fragment
</jsp:scriptlet>

Scriptlet is like a Java code island in the JavaServer Pages. Inside the island we can write Java code.
 

JSP Declarations

A declaration in JSP declares one or more variables or methods that we can use in Java code later in the JSP file.

We must declare the variable or method before using it in the JSP file, like in Java code.

Following is the syntax of JSP Declarations:
<%! declaration; ... %>

You can write XML equivalent of the above syntax as follows:
<jsp:declaration>
   code fragment
</jsp:declaration>

Following is the simple example for JSP Declarations:
<%! int i = 0; %> 
<%! int a, b, c; %> 
<%! double money; %> 
<%! YourClass a = new YourClass(); %>

In the following example of JSP declaration tag, we are declaring the field and printing the value of the declared field using the jsp expression tag.

<html>
<body>

<%! int data=50; %>
<%= "Value of the variable is:"+data %>

</body>
</html>

The following example of JSP declaration tag defines the method which returns the cube of given number and calls this method from the jsp expression tag.

<html>
<body>

<%! 
int cube(int n){
return n*n*n*;
}
%>

<%= "Cube of 3 is:"+cube(3) %>

</body>
</html>


JSP Expression

A JSP expression element contains a scripting language expression that is evaluated, converted to a String.

The expression element can have any valid Java expression without a semicolon at the end.

The following code shows the syntax of JSP Expression:
<%= expression %>

In the following example of jsp expression tag, we display a welcome message.

<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>

The XML equivalent of the above syntax is as follows:
<jsp:expression>
   expression
</jsp:expression>

The following code shows how to use JSP Expression.
<html> 
<body>
<p>
   Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body> 
</html>

This would generate following result:
<p> Today's date: 11-Jan-2015 17:02:25 </p>
 

JSP Comments

The following code shows the syntax of JSP comments:
<%-- This is JSP comment --%>

The following JSP has a JSP Comment.
<html> 
<body> 
<%-- This is a comment in the page.--%> 
</body> 
</html>
<!-- comment --> is an HTML comment. Ignored by the browser.

JSP Directives

A JSP directive sets the overall structure of the servlet class.
It usually has the following form:
 
<%@ directive attribute="value" %>

There are three types of directive tag:

Directive Description
<%@ page ... %>    Defines page-dependent attributes, such as scripting language, error page, 
    and buffering requirements.
<%@ include ... %>    Includes a file to use in the current page.
<%@ taglib ... %>     Declares a tag library, containing custom actions

JSP Actions

JSP actions use commands in XML syntax to control the behavior of the servlet engine
which controls how to generate the JavaServer Pages.

We can insert a file, use JavaBeans code, forward the user to another page,
or generate HTML for the Java plugin by using the JSP Actions.

JSP Actions use the following syntax:
 
<jsp:action_name attribute="value" />

The following table lists the JSP actions available.

Syntax Purpose
jsp:includeIncludes a file
jsp:useBeanInstantiates a JavaBean
jsp:setPropertySets the property of a JavaBean
jsp:getPropertyInserts the property of a JavaBean into the output
jsp:forwardForwards the requester to a new page
jsp:pluginGenerates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:elementDefines XML elements.
jsp:attributeDefines XML element's attribute.
jsp:bodyDefines XML element's body.
jsp:textWrite template text in JSP pages and documents.

JSP Implicit Objects

JSP supports nine implicit objects. They are listed in the following table.

Objects Description
requestRepresents the HttpServletRequest object associated with the request.
responseRepresents the HttpServletResponse object associated with the response to the client.
outReferences to the PrintWriter object to send output to the client.
sessionHttpSession object associated with the request.
applicationServletContext object associated with application context.
configServletConfig object associated with the page.
pageContextpage context object.
pageIt is a synonym for this, and is used to call the methods in translated servlet class.
ExceptionUsed Exception object to access the exception data.
 

JSP if...else

We can use if statement in JavaServer Pages.
The if...else block works as normal if...else statement.
We need to use Scriptlet at each line with HTML text included between
Scriptlet tags.

The following code shows how to use the if...else statement with Scriptlet tags.

<%! int day = 7; %> 
<html> 
<body>
<% if (day == 1) { %>
      <p> is one </p>
<% } else { %>
      <p> not one</p>
<% } %>
</body> 
</html>
 

JSP Switch...case

The following code shows how to use switch...case block

<%! int day = 3; %> 
<html> 
<body>
<% 
switch(day) {
case 0:
   out.println("It\'s Sunday.");
   break;
case 1:
   out.println("It\'s Monday.");
   break;
case 2:
   out.println("It\'s Tuesday.");
   break;
case 3:
   out.println("It\'s Wednesday.");
   break;
case 4:
   out.println("It\'s Thursday.");
   break;
case 5:
   out.println("It\'s Friday.");
   break;
default:
   out.println("It's Saturday.");
}
%>
</body> 
</html>
 
 

JSP for loop

The following code shows how to use for loop.
<%! int fontSize; %> 
<html> 
<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
   <font color="red" size="<%= fontSize %>">
    JSP Tutorial
   </font><br />
<%}%>
</body> 
</html>
 

JSP while loop

The following code shows how to use while loop.
<%! int fontSize; %> 
<html> 
<head><title>WHILE LOOP Example</title></head> 
<body>
<%while ( fontSize <= 3){ %>
   <font color="green" size="<%= fontSize %>">
    JSP Tutorial
   </font><br />
<%fontSize++;%>
<%}%>
</body> 
</html>
 
 
JSP directives provide instructions to the JSP engine on how to handle JSP.
A JSP directive affects the structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
Directives can have a list of attributes defined in key-value pairs and separated by commas.

Directive Tags

There are three types of directive tag:
Directive Description
<%@ page ... %>Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include ... %>Includes another file.
<%@ taglib ... %>Declares a tag library containing custom actions which can be used in the page.
 
 

The page Directive

The page directive instructs JSP engine on how to process the current JSP page.
We can add page directives anywhere in the JSP page.

By convention, page directives are listed at the top of the JSP page.

The following example shows the basic syntax of page directive:
<%@ page attribute="value" %>

You can write XML equivalent of the above syntax as follows:
<jsp:directive.page attribute="value" />

 

Page directive Attributes

The following lists of attributes associated with page directive.

Attribute Description
bufferSet a buffering model for the output stream.
autoFlushSet behavior of the servlet output buffer.
contentTypeSet the character encoding scheme.
errorPageSet the URL of another JSP for Java unchecked runtime exceptions.
isErrorPageSet if this JSP page is used by another JSP page as errorPage.
extendsSet a superclass that the generated servlet must extend
importA list of packages as Java import statement in the JSP.
infoProvides a string that will be returned from the servlet's getServletInfo() method.
isThreadSafeSet the threading model for the generated servlet.
languageDefines the programming language used in the JSP page.
sessionSpecifies whether or not the JSP page is in HTTP sessions
isELIgnoredWhether to igore EL expression within the JSP page.
isScriptingEnabledDetermines if scripting elements are allowed.
 
 

The include Directive

The include directive includes a file into the current JSP page.
This directive merges the content from external files with the current JSP
during the translation phase.

You may code include directives anywhere in your JSP page.

The include directive has the following syntax:
<%@ include file="relative url" >

The XML equivalent of the above syntax is as follows:
<jsp:directive.include file="relative url" />

The taglib Directive

We can define custom JSP tags in JavaServer Pages that look like HTML tags.
A tag library is a set of user-defined tags that implement custom behavior.

The taglib directive declares a set of custom tags, identifies the location
of the library, and defines a prefix for the custom tags.

The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >

The XML equivalent of the above syntax is as follows:
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
 
 

Example of import attribute

The import attribute is used to import class,interface or all the members of a package. It is similar to import keyword in java class or interface.
<html>
<body>

<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>

</body>
</html>

Content Type

The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP response.The default value is "text/html;charset=ISO-8859-1".
<html>
<body>

<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>

</body>
</html>

Example of info attribute

info attribute sets the information of the JSP page which is retrieved later by using getServletInfo() method of Servlet interface.
<html>
<body>

<%@ page info="composed by java2s.com" %>
Today is: <%= new java.util.Date() %>

</body>
</html>

Example of buffer attribute

The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page. The default size of the buffer is 8Kb.
<html>
<body>

<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>

</body>
</html>

Example of errorPage attribute

The errorPage attribute is used to define the error page, if exception occurs in the current page, it will be redirected to the error page.
//index.jsp
<html>
<body>

<%@ page errorPage="myerrorpage.jsp" %>

 <%= 100/0 %>

</body>
</html>

Example of isErrorPage attribute

The isErrorPage attribute is used to declare that the current page is the error page.
The exception object can only be used in the error page.
//myerrorpage.jsp
<html>
<body>

<%@ page isErrorPage="true" %>

 Sorry an exception occured!<br/>
The exception is: <%= exception %>

</body>
</html>
 
JSP actions controls the behavior of the underneath servlet engine.  With JSP actions we can dynamically insert a file,  reuse JavaBeans components, or forward the user to another page.
The following code is the syntax for the Action element:
<jsp:action_name attribute="value" />

Example

We can use the following JSP actions.
Syntax Purpose
jsp:includeIncludes a file
jsp:useBeanInitialize a JavaBean
jsp:setPropertySets the property of a JavaBean
jsp:getPropertyGet the property from a JavaBean
jsp:forwardForwards the request to another page
jsp:pluginGenerates an OBJECT or EMBED tag for the Java plugin
jsp:elementDefines XML elements dynamically.
jsp:attributeDefines XML element's attribute.
jsp:bodyDefines XML element's body.
jsp:textWrite template text in JSP pages and documents.
 
 
 

Common Attributes in JSP Actions

There are two common attributes for all Action elements: the id attribute and the scope attribute.
Id attribute uniquely identifies the Action element. We can use the id to reference the action in the JSP page.
Scope attribute identifies the lifecycle of the Action element. The scope attribute has four possible values:
  • page
  • request
  • session
  • application

jsp:include Action

jsp:include Action inserts files into the JSP pages. The syntax is listed as follows:
<jsp:include page="relative URL" flush="true" />
The include directive includes a file at the time the JSP page is translated into a servlet, while jsp:include action inserts the file at the time the page is requested.
The following table lists the attributes associated with include action.
Attribute Description
pageThe relative URL of the page to be included.
flushThe boolean attribute determines whether the included resource should have its buffer flushed before including.
The following code shows how to use include action.
Here is the data.jsp.
<p>
   Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
Here is the content of main.jsp file:
<html>
<body>
<jsp:include page="date.jsp" flush="true" />
</body>
</html>
 
 

jsp:useBean Action

The useBean action first searches for an existing object using the id and scope attributes. If an object is not found, it then will create the specified object.
The simplest way to load a bean is as follows:
<jsp:useBean id="name" class="java.lang.String" />
<jsp:useBean id="yourName" class="com.yourCom.YourClassName" />
Once a bean is loaded, we can use jsp:setProperty and jsp:getProperty actions to modify and retrieve bean properties.
The following table list attributes associated with useBean action.
Attribute Description
classDefines the full package name of the bean.
typeSpecifies the type of the variable.
beanNameNamed the loaded bean.

jsp:setProperty Action

The setProperty action sets the properties of a Bean.
We can use jsp:setProperty after outside of a jsp:useBean element as follows.
<jsp:useBean id="myName" ... />
<jsp:setProperty name="myName" property="someProperty" .../>
Or we can include jsp:setProperty inside the body of a jsp:useBean element as follows.
<jsp:useBean id="myName" ... >
    ...
    <jsp:setProperty name="myName" property="someProperty" .../>
</jsp:useBean>
In the code above, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.
The following table lists the attributes associated with setProperty action.
Attribute Description
nameThe name of the bean whose property will be set.
propertyProperty to set. A value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods.
valueValue to set to the property.
paramThe param attribute is the name of the request parameter.
 
 
 

jsp:getProperty Action

The getProperty action retrieves the value of a given property and converts it to a string, and then inserts it into the output.
The getProperty action has two attributes listed as follows:
<jsp:useBean id="myName" ... />
...
<jsp:getProperty name="myName" property="someProperty" .../>
Following is the list of required attributes associated with getProperty action.
Attribute Description
nameThe name of the Bean which must have been previously defined.
propertyThe name of the Bean property.

Example for userBean, set/get Property

Create a JavaBean as follows.
package action;
 
public class TestBean {
   private String message = "No message specified";
 
   public String getMessage() {
      return(message);
   }
   public void setMessage(String message) {
      this.message = message;
   }
}
Compile above code to TestBean.class file and copy TestBean.class to C:\apache-tomcat\webapps\WEB-INF\classes\action folder.
Save the following code to hellow.jsp file.
<html>
<body>
<jsp:useBean id="test" class="action.TestBean" />
<jsp:setProperty name="test" 
                    property="message" 
                    value="Hello JSP..." />
<jsp:getProperty name="test" property="message" />
</body>
</html>

The jsp:forward Action

The forward action forwards the request to another a static page, or another JSP page, or a Java Servlet.
The simple syntax of this action is as follows:
<jsp:forward page="relativeURL | <%= expression %>" />
The following table lists the required attributes for forward action.
Attribute Description
pageRelative URL for another resource.
The following code shows how to use the forward action.
The date.jsp file:
<p>
   Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
Here is the main.jsp file:
<html>
<body>
<jsp:forward page="date.jsp" />
</body>
</html>

The jsp:plugin Action

The plugin action can insert Java applet, wrapped in the <object> or <embed> tags, into a JSP page.
The following code lists the typical syntax of using plugin action.
<jsp:plugin type="applet" codebase="dirname" code="MyApplet.class"
                           width="60" height="80">
   <jsp:param name="fontcolor" value="red" />
   <jsp:param name="background" value="black" />
 
   <jsp:fallback>
      Unable to initialize Java Plugin
   </jsp:fallback>
 
</jsp:plugin>

The jsp:body Action

The <jsp:element>, <jsp:attribute> and <jsp:body> actions defines XML elements dynamically.
The following code shows how to define XML elements dynamically.
<%@page language="java" contentType="text/html"%>
<html xmlns="http://www.w3c.org/1999/xhtml"
      xmlns:jsp="http://java.sun.com/JSP/Page">
<body>
    <jsp:element name="xmlElement">
    <jsp:attribute name="xmlElementAttr">
       Value
    </jsp:attribute>
    <jsp:body>
       Body
    </jsp:body>
    </jsp:element>
</body>
</html>

 
 
JSP Implicit Objects are the Java objects available in each page and can be used directly without explicitly declaration.  The following table lists nine Implicit Objects.
Object Description
requestHttpServletRequest object associated with the request. Each time a client requests a page the JSP engine creates a new object to represent that request. We can use the request object to get HTTP header information such as form data, cookies, HTTP methods etc.
responseHttpServletResponse object associated with the response to the client. JSP engine creates an object to represent the response to the client. We can use this object to add new cookies or date stamps, HTTP status codes etc to the response.
outPrintWriter object used to send output to the client. We can use buffer in the output by using the buffered='false' attribute of the page directive. out.print(dataType dt) prints a data type value. out.println(dataType dt) prints a data type value then terminate the line with new line character. out.flush() flushes the stream.
sessionHttpSession object associated with the request. The session object tracks client session between client requests.
applicationServletContext object associated with application context. This object reoresents the JSP page through the entire lifecycle. It is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
configServletConfig object associated with the page. We can use this object to access the Servlet or JSP engine initialization parameters such as the paths or file locations etc. config.getServletName() returns the servlet name , which is the string contained in the <servlet-name> element defined in the WEB-INF\web.xml file.
pageContextThe pageContext object is an instance of a javax.servlet.jsp.PageContext object, which is used to represent the entire JSP page. This object contains informations about the request and response objects for each request. We can also get the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope from this object. The PageContext class defines fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE to identify the four scopes.
pageA synonym for this, and is used to call the methods defined by the translated servlet class.
ExceptionException object used to access the exception data by JSP.
 
 
 
 

JSP Hits Counter

To implement a hit counter, use getAttribute() and setAttribute() from Application implicit object, which is a representation of the JSP page.
The following code shows the syntax to set/get a variable at application level:
application.setAttribute(String Key, Object Value);
application.getAttribute(String Key);
The following code shows how to count total number of hits on a particular page.
<%@ page import="java.io.*,java.util.*" %>

<html>
<body>
<%
    Integer hitsCount = (Integer)application.getAttribute("hitCounter");
    if( hitsCount ==null || hitsCount == 0 ){
       out.println("first time!");
       hitsCount = 1;
    }else{
       /* return visit */
       out.println("Welcome back!");
       hitsCount += 1;
    }
    application.setAttribute("hitCounter", hitsCount);
%>
<p>Total number of visits: <%= hitsCount%></p>
</body>
</html>
 
 
 
When a browser requests a web page, it sends information to the web server in the  HTTP header.
We can access the information sent to the server with javax.servlet.http.HttpServletRequest object.
The request object provides methods to get HTTP header information including form data, cookies, HTTP methods etc.
The following listed methods can be used to read HTTP header in JSP page.
MethodDescription
Cookie[] getCookies()Returns an array containing all of the Cookie objects the client sent.
Enumeration getAttributeNames()Returns an Enumeration containing the names of the attributes for this request.
Enumeration getHeaderNames()Returns an enumeration of all the header names.
Enumeration getParameterNames()Returns an Enumeration of String objects containing the names of the parameters
HttpSession getSession()Returns the current session. If the request does not have a session, creates a new one and return.
HttpSession getSession(boolean create)Returns the current HttpSession or, if there is no current session and create is true, returns a new session.
Locale getLocale()Returns the preferred Locale for the client, based on the Accept-Language header
Object getAttribute(String name)Returns the value of the named attribute, or null if no attribute for the given name.
ServletInputStream getInputStream()Retrieves the body of the request as binary data using a ServletInputStream.
String getAuthType()Returns the name of the authentication scheme used to protect the servlet, for example, "BASIC" or "SSL," or null.
String getCharacterEncoding()Returns the name of the character encoding.
String getContentType()Returns the MIME type, or null if the type is not known.
String getContextPath()Returns the portion of the request URI that indicates the context of the request.
String getHeader(String name)Returns the value of the specified request header as a String.
String getMethod()Returns the name of the HTTP method, for example, GET, POST, or PUT.
String getParameter(String name)Returns the value of a request parameter as a String, or null if the parameter does not exist.
String getPathInfo()Returns path information associated with the URL the client sent.
String getProtocol()Returns the name and version of the protocol for the request.
String getQueryString()Returns the query string contained in the request URL after the path.
String getRemoteAddr()Returns IP address of the client.
String getRemoteHost()Returns the fully qualified name of the client.
String getRemoteUser()Returns the login of the user, or null if the user has not been authenticated.
String getRequestURI()Returns request's URL from the protocol name up to the query string.
String getRequestedSessionId()Returns the session ID
String getServletPath()Returns request's URL that calls the JSP.
String[] getParameterValues(String name)Returns String arrays containing all of the values the given request parameter has
boolean isSecure()Returns a boolean indicating if the request is from a secure channel, such as HTTPS.
int getContentLength()Returns the length, in bytes, of the request, or -1 if the length is not known.
int getIntHeader(String name)Returns the value of the specified request header as an int.
int getServerPort()Returns the port number on which this request was received.
 
 
 

Example

The following code shows how to use getHeaderNames() method of HttpServletRequest to read the HTTP header infromation.
<%@ page import="java.io.*,java.util.*" %>
<html>
<body>
<table width="100%" border="1" align="center">
<tr bgcolor="#949494">
<th>Header Name</th><th>Header Value(s)</th>
</tr>
<%
   Enumeration headerNames = request.getHeaderNames();
   while(headerNames.hasMoreElements()) {
      String paramName = (String)headerNames.nextElement();
      out.print("<tr><td>" + paramName + "</td>\n");
      String paramValue = request.getHeader(paramName);
      out.println("<td> " + paramValue + "</td></tr>\n");
   }
%>
</table>
</body>
</html>
 
With JSP we can access a Web server HTTP response to the browser. The response object is an instance of a  javax.servlet.http.HttpServletResponse object.  
We can use the following methods to set HTTP response header in your servlet program.
MethodDescription
String encodeRedirectURL(String url)Encodes the URL in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.
String encodeURL(String url)Encodes the URL by including the session ID, or, if encoding is not needed, returns the URL unchanged.
boolean containsHeader(String name)Returns a boolean indicating whether the named header has been set.
boolean isCommitted()Returns a boolean indicating if the response has been committed.
void addCookie(Cookie cookie)Adds the cookie to the response.
void addDateHeader(String name, long date)Adds a response header with the given name and date-value.
void addHeader(String name, String value)Adds a response header with the given name and value.
void addIntHeader(String name, int value)Adds a response header with the given name and integer value.
void flushBuffer()Forces content in the buffer to output to the client.
void reset()Clears data in the buffer, the status code and headers.
void resetBuffer()Clears the buffer content in the response without clearing headers or status code.
void sendError(int sc)Sends an error response to the client with the specified status code and clear the buffer.
void sendError(int sc, String msg)Sends an error response to the client using the specified status.
void sendRedirect(String location)Sends a temporary redirect response to the client using the specified redirect location URL.
void setBufferSize(int size)Sets the preferred buffer size for the response body.
void setCharacterEncoding(String charset)Sets the character encoding of the response, for example, to UTF-8.
void setContentLength(int len)Sets the length of the content body in the response(HTTP Content-Length header).
void setContentType(String type)Sets the content type of the response, if the response has not been committed yet.
void setDateHeader(String name, long date)Sets a response header with the given name and date-value.
void setHeader(String name, String value)Sets a response header with the given name and value.
void setIntHeader(String name, int value)Sets a response header with the given name and integer value.
void setLocale(Locale loc) Sets the locale of the response, if the response has not been committed yet.
void setStatus(int sc)Sets the status code for this response.
 
 

HTTP Header Response Example

The following code shows how to use setIntHeader() method to set Refresh header to simulate a digital clock.
<%@ page import="java.io.*,java.util.*" %>
<html>
<body>
<center>
<%
   // Set refresh, autoload time as 5 seconds
   response.setIntHeader("Refresh", 5);
   // Get current time
   Calendar calendar = new GregorianCalendar();
   String am_pm;
   int hour = calendar.get(Calendar.HOUR);
   int minute = calendar.get(Calendar.MINUTE);
   int second = calendar.get(Calendar.SECOND);
   if(calendar.get(Calendar.AM_PM) == 0)
      am_pm = "AM";
   else
      am_pm = "PM";
   String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
   out.println("Current Time is: " + CT + "\n");
%>
</center>
</body>
</html>
 
 
 

HTTP Status Code Example

The following code shows how to send 407 error code to the client browser.
<html>
<body>
<%
   response.sendError(407, "Need authentication!!!" );
%>
</body>
</html>

Page Redirecting

Page redirection is used when a document moves to a new location.
We can do page redirecting using method sendRedirect() from response object.
It has the following signature:
public void response.sendRedirect(String location)
throws IOException
<%@ page import="java.io.*,java.util.*" %>
<html>
<body>
<h1>Page Redirection</h1>
<%
   String site = new String("http://www.java2s.com");
   response.setStatus(response.SC_MOVED_TEMPORARILY);
   response.setHeader("Location", site); 
%>
</body>
</html>

Auto Refresh

We can use method setIntHeader() from response object to set interval for page refresh.
public void setIntHeader(String header, int headerValue)
This method can send back header "Refresh" to the browser along with an integer indicating time interval in seconds.
The following code shows how to do page refresh.
<%@ page import="java.io.*,java.util.*" %>
<html>
<body>
<%
   response.setIntHeader("Refresh", 5);
   Calendar calendar = new GregorianCalendar();
   String am_pm;
   int hour = calendar.get(Calendar.HOUR);
   int minute = calendar.get(Calendar.MINUTE);
   int second = calendar.get(Calendar.SECOND);
   if(calendar.get(Calendar.AM_PM) == 0)
      am_pm = "AM";
   else
      am_pm = "PM";
   String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
   out.println( CT + "\n");
%>
</body>
</html>


 
To send information to web server, we can use two methods: GET Method and POST Method.
The GET method sends the encoded user information separated by the ? character appended to the page URL.
http://www.java2s.com/hello?key1=value1&key2=value2
The GET method is the default method to send information to web server. Since the GET method appends plain text string to the URL. We should avoid using GET method to send password or other sensitive information to the server.
The GET method also has size limitation. We can send only 1024 characters in a request string. This information sent is accessible getQueryString() and getParameter() methods of request object.
POST method is more reliable method of sending information to the server. This method sends the information as a separate message.
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.
JSP handles form data using the following methods.
MethodDescription
getParameter()returns the value of a form parameter.
getParameterValues()returns multiple values, for example checkbox.
getParameterNames()returns a complete list of all parameters.
getInputStream()read binary data stream coming from the client.

GET parameters from URL

The following code shows how to get parameters using GET method.
The following code uses the getParameter() method to read parameters.
<html>
<body>
<b>First Name:</b><%= request.getParameter("first_name")%><br/>
<b>Last  Name:</b><%= request.getParameter("last_name")%>
</body>
</html>
Save the code above as main.jsp. And copy the file to the Tomcat deployment folder.
First we would type in the parameters and their value directly in the URL. Enter the following URL in your broswer address bar.
http://localhost:8080/main.jsp?first_name=James&last_name=Smith
We can use the following html form to pass the values to JSP main.jsp page.
<html>
    <body>
    <form action="main.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>

Save this HTML in a file called Hello.htm and put it in Tomcat-installation-directory/webapps/ROOT directory.
Access it with http://localhost:8080/Hello.htm
The following line in the HTML code calls the jsp page we created to accept parameter and indicates that we are going to use the GET method to pass the information.
<form action="main.jsp" method="GET">
 

POST Method Example with Form

Create a html page as follows and use POST methods for the form. Save it as Hello.htm.
<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>
Below is main.jsp JSP program to handle input from by web browser using GET or POST methods.
<html>
<body>
<b>First Name:</b><%= request.getParameter("first_name")%><br/>
<b>Last  Name:</b><%= request.getParameter("last_name")%>
</body>
</html>
 

Passing Checkbox Data to JSP

The following code shows how to use the JSP page to get the checkbox data from a form.
Here is the html form code. It uses the POST method and calls the main.jsp page.
<html>
<body>
<form action="main.jsp" method="POST" target="_blank">
    <input type="checkbox" name="a" checked="checked" /> A
    <input type="checkbox" name="b"  /> B
    <input type="checkbox" name="c" checked="checked" /> C
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
The following is the main.jsp code to handle input for checkbox button.
<html>
<body>
<b>A Flag:</b><%= request.getParameter("a")%>
<b>B Flag:</b><%= request.getParameter("b")%>
<b>C Flag:</b><%= request.getParameter("c")%>
</body>
</html>
 
 

Reading All Form Parameters

The following code shows how to use getParameterNames() method from HttpServletRequest to read all the available form parameters.
This method returns an Enumeration object that contains the parameter names.
<%@ page import="java.io.*,java.util.*" %>
<html>
<body>
<%
   Enumeration paramNames = request.getParameterNames();
   while(paramNames.hasMoreElements()) {
      String paramName = (String)paramNames.nextElement();
      out.print("<b>" + paramName + ":</b>\n");
      String paramValue = request.getHeader(paramName);
      out.println(paramValue);
   }
%>
</body>
</html>
 
JSP Filters are Java classes that can be used for  intercepting requests from a client or manipulating  responses from server.
The filters can be used to do Authentication, Encryption, Logging, Auditing.
We can map filters to either JSP names or URL patterns in application's deployment descriptor file web.xml.
The filters execute in the order that they are declared in the deployment descriptor.
A filter is a Java class that implements the javax.servlet.Filter interface.
The javax.servlet.Filter interface defines three methods:
MethodDescription
doFilter (ServletRequest, ServletResponse, FilterChain)called by the container when a request/response pair is passed through the chain.
init(FilterConfig filterConfig)indicate to a filter being placed into service.
void destroy()indicate to a filter that it is being taken out of service.

Example

The following code shows how to create a JSP Filter that prints the IP address.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
 
public class LogFilter implements Filter  {
   public void  init(FilterConfig config) 
                         throws ServletException{
      String testParam = config.getInitParameter("test-param"); 
      System.out.println("init");
   }
   public void  doFilter(ServletRequest request, 
                 ServletResponse response,
                 FilterChain chain) 
                 throws java.io.IOException, ServletException {
 
      String ipAddress = request.getRemoteAddr();
      System.out.println("IP "+ ipAddress);
 
      chain.doFilter(request,response);
   }
   public void destroy( ){
      System.out.println("destroy");
   }
}
Compile LogFilter.java and put the LogFilter.class class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.
Create the following entry for filter tag in the deployment descriptor file web.xml
<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
    <param-name>your-param</param-name>
    <param-value>Initialization Parameter</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
The above filter would apply to all the JSP because we specified /* in our configuration.
 

Multiple Filters

The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet or JSP.
The following code shows how to use two filters in web.xml file.
<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
    <param-name>test-param</param-name>
    <param-value>Initialization Parameter</param-value>
   </init-param>
</filter>
 
<filter>
   <filter-name>MyFilter</filter-name>
   <filter-class>MyFilter</filter-class>
   <init-param>
    <param-name>test-param</param-name>
    <param-value>Initialization Parameter</param-value>
   </init-param>
</filter>
 
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
 
<filter-mapping>
   <filter-name>MyFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
To reverse the filter order from the above web.xml, use the following:
<filter-mapping>
   <filter-name>MyFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
 
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
 
 
Cookies are text files stored on the client computer and are used to store information.
A JSP can access to the cookies through the request method request.getCookies() which returns an array of Cookie objects.
The following table lists useful methods associated with Cookie object.
MethodDescription
setDomain(String pattern)sets the domain for cookie, for example java2s.com.
String getDomain()gets the domain to which cookie applies.
setMaxAge(int seconds)Sets how much time in seconds should elapse before the cookie expires. By default, the cookie will last for the current session.
getMaxAge()Get cookie age in seconds. -1 indicating the cookie will persist until browser shutdown.
String getName()returns the name of the cookie, which cannot be changed after creation.
setValue(String newValue)sets the value associated with the cookie.
String getValue()gets the value associated with the cookie.
setPath(String uri)sets the path this cookie applies. By default, the cookie is returned for all URLs in the current directory and subdirectories.
String getPath()gets the path to which this cookie applies.
setSecure(boolean flag)sets to send cookie over encrypted (i.e. SSL) connections.
setComment(String purpose)Sets a comment that describes a cookie's purpose.
String getComment()get the comment for the cookie
The following code shows how to set cookies in JSP.
Cookie cookie = new Cookie("key","value");
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
 
 

Example

Save the following file as main.jsp. The top part of the main.jsp file is all in Java code wrapped in <% ... %>. The logic gets the first name and last name from the parameters then create a cookie and add the names to it. It sets the age for a cookie for one hour.
<%
   // Create cookies for first and last names.      
   Cookie firstName = new Cookie("first_name",request.getParameter("first_name"));
   Cookie lastName = new Cookie("last_name",request.getParameter("last_name"));

   // Set expiry date after one hour for both the cookies.
   firstName.setMaxAge(60*60); 
   lastName.setMaxAge(60*60); 

   // Add both the cookies in the response header.
   response.addCookie( firstName );
   response.addCookie( lastName );
%>
<html>
<body>
<ul>
<b>First Name:</b><%= request.getParameter("first_name")%><br/>
<b>Last  Name:</b><%= request.getParameter("last_name")%>
</body>
</html>
The following HTML page is to call the main.jsp.
<html>
<body>
<form action="main.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>
 
 

Reading Cookies with JSP

To read cookies, create an array of javax.servlet.http.Cookie objects by calling the getCookies() method from HttpServletRequest.
Then loop through the array, and use getName() and getValue() methods to access each cookie and associated value.
The following code shows how to read cookies set in previous example.
<html>
<body>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   cookies = request.getCookies();
   if( cookies != null ){
      for (int i = 0; i < cookies.length; i++){
         cookie = cookies[i];
         out.print("Name : " + cookie.getName( ) + ",  ");
         out.print("Value: " + cookie.getValue( )+" <br/>");
      }
  }else{
      out.println("<h2>No cookies founds</h2>");
  }
%>
</body>
</html>
 

Delete cookies

To delete cookies, set cookie age to zero using setMaxAge() method.
The following code shows how to delete a cookie. It only deletes the cookie named first_name
<html>
<body>
<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   cookies = request.getCookies();
   if( cookies != null ){
      for (int i = 0; i < cookies.length; i++){
         cookie = cookies[i];
         if((cookie.getName( )).compareTo("first_name") == 0 ){
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            out.print("Deleted cookie: " + cookie.getName( ) + "<br/>");
         }
         out.print("Name : " + cookie.getName( ) + ",  ");
         out.print("Value: " + cookie.getValue( )+" <br/>");
      }
  }
%>
</body>
</html>
 
 
 
HTTP is a "stateless" protocol. Each time a client uses a new connection to talk to the server and the server does not keep any record of previous request.
There are three ways to keep the records of client.
  • Cookies - When using cookie, server can assign a unique ID to each web client and recognize the client by using that ID.
  • Hidden Form Fields - Server can send a hidden HTML form field along with a unique session ID. When the form is submitted, the specified name and value are automatically included in the GET or POST data.
  • URL Rewriting - We can append client ID to the end of URL to identify the user. For example, with http://java2s.com/abc/index.htm;sessionid=123. URL rewriting works for the browsers when they don't support cookies.
JSP uses HttpSession to work with session data.
By default, JSPs have session enabled and a new HttpSession object is created for each new client.
To disable the session tracking use the following code.
<%@ page session="false" %>
In JSP page we can use the HttpSession object with the implicit session object.
The following table lists the useful methods from session object:
MethodDescription
Object getAttribute(String name)returns the object bound with the specified name in session, or null.
Enumeration getAttributeNames()returns an Enumeration of String objects for the names of all the objects in session.
long getCreationTime()returns the session creation time in milliseconds since midnight January 1, 1970 GMT.
String getId()returns a string containing the unique identifier for this session.
long getLastAccessedTime()returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
int getMaxInactiveInterval()returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
void invalidate()invalidates this session.
boolean isNew()returns true if the session is new to the client.
removeAttribute(String name)removes the object by name from the session.
void setAttribute(String name, Object value)binds an object to session by name
void setMaxInactiveInterval(int interval)Sets the time, in seconds, between client requests before the servlet container will invalidate this session.

Example

The following code shows how to use the HttpSession object.
<%@ page import="java.io.*,java.util.*" %>
<%
   Date createTime = new Date(session.getCreationTime());
   Date lastAccessTime = new Date(session.getLastAccessedTime());

   String title = "Welcome Back";
   Integer visitCount = new Integer(0);
   String visitCountKey = "visitCount";
   String userIDKey = new String("userID");
   String userID = new String("Java2s_ID");

   if (session.isNew()){
      title = "Welcome";
      session.setAttribute(userIDKey, userID);
      session.setAttribute(visitCountKey,  visitCount);
   } 
   visitCount = (Integer)session.getAttribute(visitCountKey);
   visitCount = visitCount + 1;
   userID = (String)session.getAttribute(userIDKey);
   session.setAttribute(visitCountKey,  visitCount);
%>
<html>
<body>
id:<% out.print( session.getId()); %><br/>
Creation Time:<% out.print(createTime); %><br/>
Time of Last Access:<% out.print(lastAccessTime); %><br/>
User ID:<% out.print(userID); %>
Number of visits:<% out.print(visitCount); %><br/>
</body>
</html>
Save the above code in main.jsp and try to access http://localhost:8080/main.jsp
 
 

Deleting Session Data

To remove an attribute, call removeAttribute(String name) method.
To delete the whole session, call invalidate() method to delete an entire session.
To set Session timeout, call setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
We use the following xml tags in web.xml to set the session timeout time in minutes.
<session-config>
    <session-timeout>15</session-timeout>
  </session-config>
The default timeout is 30 minutes in Tomcat.
The getMaxInactiveInterval( ) method returns the timeout period in seconds.


We can upload text file, binary or image file to the server by using JSP.
The following sections how to create client side form and server script to upload a file to the server.

Example

The following html code below creates a form to upload file.
The form method attribute should be set to POST method and we cannot use GET method to upload a file.
The form enctype attribute is set to multipart/form-data.
The form action attribute is set to a JSP file which would handle file uploading from server.
<html>
<body>
Select a file to upload: <br />
<form action="fileupload.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
The next step is to create Server side logic in JSP page.
The JSP file use the file-upload and common-io libraries.
Include the commons-fileupload.jar and commons-fileupload.jar in the classpath.
We can download those files from http://commons.apache.org/.
Create directories c:\temp and c:\apache-tomcat\webapps\data in advance.
Here is the JSP file to handle the file upload.
<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>

<%
   File file ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   String filePath = "c:/apache-tomcat/webapps/data/";

   String contentType = request.getContentType();
   if ((contentType.indexOf("multipart/form-data") >= 0)) {

      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setSizeThreshold(maxMemSize);
      factory.setRepository(new File("c:\\temp"));
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setSizeMax( maxFileSize );
      try{ 
         List fileItems = upload.parseRequest(request);
         Iterator i = fileItems.iterator();
         out.println("<html>");
         out.println("<body>");
         while ( i.hasNext () ) 
         {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () )  {
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                file = new File( filePath + "yourFileName") ;
                fi.write( file ) ;
                out.println("Uploaded Filename: " + filePath + fileName + "<br>");
            }
         }
         out.println("</body>");
         out.println("</html>");
      }catch(Exception ex) {
         System.out.println(ex);
      }
   }else{
      out.println("<html>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>"); 
      out.println("</body>");
      out.println("</html>");
   }
%>
Try http://localhost:8080/UploadFile.htm and upload a small file. The file should be uploaded in c:/apache-tomcat/webapps/data/ directory.


To send an email using a JSP, install JavaMail API and Java Activation Framework (JAF) in CLASSPATH.

Send an Email

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%
   String result;
   String to = "to@gmail.com";
   String from = "from@gmail.com";
   String host = "localhost";
   Properties properties = System.getProperties();
   properties.setProperty("mail.smtp.host", host);
   Session mailSession = Session.getDefaultInstance(properties);
   try{
      MimeMessage message = new MimeMessage(mailSession);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
      message.setSubject("This is the Subject Line!");
      message.setText("This is actual message");
      Transport.send(message);
      result = "Sent message successfully....";
   }catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: unable to send message....";
   }
%>
<html>
<body>
<center>
</center>
<p align="center">
<% 
   out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>
To send an email to multiple recipients, use the following method.
void addRecipients(Message.RecipientType type, Address[] addresses)
throws MessagingException
 

Send an HTML Email

Use the following function and parameter to send an HTML email out.
message.setContent("<h1>This is actual message</h1>","text/html" );
Full source code
<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%
   String result;
   String to = "to@gmail.com";
   String from = "from@gmail.com";
   String host = "localhost";
   Properties properties = System.getProperties();
   properties.setProperty("mail.smtp.host", host);
   Session mailSession = Session.getDefaultInstance(properties);
   try{
      MimeMessage message = new MimeMessage(mailSession);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
      message.setSubject("This is the Subject Line!");
      message.setContent("<h1>This is actual message</h1>","text/html" );
      Transport.send(message);
      result = "Sent message successfully....";
   }catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: unable to send message....";
   }
%>
<html>
<body>
<p align="center">
<% 
   out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>

Send Email with Attachment

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%
   String result;
   String to = "to@gmail.com";
   String from = "from@gmail.com";
   String host = "localhost";
   Properties properties = System.getProperties();
   properties.setProperty("mail.smtp.host", host);
   Session mailSession = Session.getDefaultInstance(properties);
   try{
      MimeMessage message = new MimeMessage(mailSession);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
      message.setSubject("This is the Subject Line!");
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setText("This is message body");
      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);
      messageBodyPart = new MimeBodyPart();
      String filename = "file.txt";
      DataSource source = new FileDataSource(filename);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(filename);
      multipart.addBodyPart(messageBodyPart);
      message.setContent(multipart );
      Transport.send(message);
      String title = "Send Email";
      result = "Sent message successfully....";
   }catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: unable to send message....";
   }
%>
<html>
<body>
<% 
   out.println("Result: " + result + "\n");
%>
</body>
</html>
 
 

User Authentication

To provide user ID and Password to the email server, set the user name and password in properties as follows:
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
 
 
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags.
The JSTL tags can be grouped as:
  • Core Tags
  • Formatting tags
  • SQL tags
  • XML tags
  • JSTL Functions
 

Core Tags

The following code shows the syntax to include JSTL Core library in JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
TagDescription
<c:out >Like <%= ... >, but for expressions.
<c:set >Sets the result of an expression evaluation
<c:remove >Removes a scoped variable from a particular scope, if specified.
<c:catch>Catches Throwable in its body and optionally exposes it.
<c:if>if statement.
<c:choose>Conditional tag for mutually exclusive conditional operations, marked by <when> and <otherwise>
<c:when>Work with <choose> to include its body if the condition is 'true'.
<c:otherwise >Together with <choose> to run if all prior conditions are 'false'.
<c:import>Retrieves a URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varReader'.
<c:forEach >Iteration tag.
<c:forTokens>Iterates over tokens, separated by the supplied delimeters.
<c:param>Adds a parameter to a containing 'import' tag's URL.
<c:redirect >Redirects to a new URL.
<c:url>Creates a URL with optional query parameters
 
 

Formatting tags

JSTL formatting tags formats and displays text, the date/time, and numbers.
The following code shows how to include format tags.
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
TagDescription
<fmt:formatNumber>Format numerical value.
<fmt:parseNumber>Parses the string to a number, currency, or percentage.
<fmt:formatDate>Format a date/time
<fmt:parseDate>Parses the string to create a date/time
<fmt:bundle>Loads a resource bundle.
<fmt:setLocale>Set the given locale.
<fmt:setBundle>Loads a resource bundle
<fmt:timeZone>Set the time zone for time formatting
<fmt:setTimeZone>Stores the given time zone in the time zone configuration variable
<fmt:message>To display an internationalized message.
<fmt:requestEncoding>Sets the request character encoding
 

SQL tags

JSTL SQL tag library is used to work with databases.
Use the following syntax to include JSTL SQL library in JSP:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
TagDescription
<sql:setDataSource>Creates a DataSource
<sql:query>Executes the SQL query in its body or the sql attribute.
<sql:update>Executes the SQL update in its body or the sql attribute.
<sql:param>Sets a parameter in an SQL statement to the specified value.
<sql:dateParam>Sets a parameter in an SQL statement to the specified java.util.Date value.
<sql:transaction >Work with transaction.

XML tags

JSTL XML tags are used to create and manipulate XML documents.
We can use the following syntax to include JSTL XML library in a JSP.
<%@ taglib prefix="x" 
           uri="http://java.sun.com/jsp/jstl/xml" %>
It can parse XML, transform XML data, and work with XPath expressions.
It depends on the following two jar files.
Install those jar files into your <Tomcat Installation Directory>\lib:
TagDescription
<x:out>Like <%= ... >, but for XPath expressions.
<x:parse>Parse XML data in an attribute or in the tag body.
<x:set >Sets value to a variable in an XPath expression.
<x:if >if statement on a XPath expression
<x:forEach>To loop over nodes in an XML document.
<x:choose>Conditional tag, and work with <when> and <otherwise>
<x:when >Work with <choose> for 'true' condition
<x:otherwise >Work with of <choose> for 'false' condition
<x:transform >Applies an XSL transformation on a XML document
<x:param >Work with the transform tag to set a parameter in the XSLT stylesheet.

JSTL Functions

JSTL has standard functions for string manipulation.
Use the following syntax to include JSTL Functions library in a JSP
<%@ taglib prefix="fn" 
           uri="http://java.sun.com/jsp/jstl/functions" %>
FunctionDescription
fn:contains()Tests if a string contains a substring.
fn:containsIgnoreCase()Tests if a string contains a substring in a case insensitive way.
fn:endsWith()Tests if an input string ends with the suffix.
fn:escapeXml()Escapes characters for XML markup.
fn:indexOf()Returns the index within a string of the first occurrence of a substring.
fn:join()Joins all elements of an array into a string.
fn:length()Returns the number of items in a collection, or the number of characters in a string.
fn:replace()Replace in an input string with a given string.
fn:split()Splits a string into an array of substrings.
fn:startsWith()If an input string starts with the prefix.
fn:substring()Returns a sub string.
fn:substringAfter()Returns a sub string following a specific substring.
fn:substringBefore()Returns a subset of a string before a specific substring.
fn:toLowerCase()Converts a string to lower case.
fn:toUpperCase()Converts a string to upper case.
fn:trim()Removes white spaces from both ends of a string.
 

SELECT Operation

The following example shows how to use SQL SELECT statement using JTSL in JSP.
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
 
<html>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost/TEST"
     user="root"  password="pass123"/>
 
<sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
</sql:query>
 
<table>
<tr>
   <th>Emp ID</th>
   <th>First Name</th>
   <th>Last Name</th>
   <th>Age</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
   <td><c:out value="${row.id}"/></td>
   <td><c:out value="${row.first}"/></td>
   <td><c:out value="${row.last}"/></td>
   <td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>
 
</body>
</html>

INSERT Operation

The following example shows how to execute SQL INSERT statement using JTSL in JSP.
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
 
<html>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost/TEST"
     user="root"  password="pass123"/>


<sql:update dataSource="${snapshot}" var="result">
INSERT INTO Employees VALUES (104, 2, 'FirstName', 'LastName');
</sql:update>
 
<sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
</sql:query>
 
<table border="1" width="100%">
<tr>
   <th>Emp ID</th>
   <th>First Name</th>
   <th>Last Name</th>
   <th>Age</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
   <td><c:out value="${row.id}"/></td>
   <td><c:out value="${row.first}"/></td>
   <td><c:out value="${row.last}"/></td>
   <td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>
 
</body>
</html>
 

DELETE Operation

The following example shows how to execute SQL DELETE statement using JTSL in JSP.
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
 
<html>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost/TEST"
     user="root"  password="pass123"/>
 
<c:set var="empId" value="103"/>
 
<sql:update dataSource="${snapshot}" var="count">
  DELETE FROM Employees WHERE Id = ?
  <sql:param value="${empId}" />
</sql:update>
 
<sql:query dataSource="${snapshot}" var="result">
   SELECT * from Employees;
</sql:query>
 
<table border="1" width="100%">
<tr>
   <th>Emp ID</th>
   <th>First Name</th>
   <th>Last Name</th>
   <th>Age</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
   <td><c:out value="${row.id}"/></td>
   <td><c:out value="${row.first}"/></td>
   <td><c:out value="${row.last}"/></td>
   <td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>
 
</body>
</html>
 
 

UPDATE Operation

The following example shows how to execute SQL UPDATE statement using JTSL in JSP.
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
 
<html>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
     url="jdbc:mysql://localhost/TEST"
     user="root"  password="pass123"/>
 
<c:set var="empId" value="102"/>
 
<sql:update dataSource="${snapshot}" var="count">
  UPDATE Employees SET last = 'LastName'
  <sql:param value="${empId}" />
</sql:update>
 
<sql:query dataSource="${snapshot}" var="result">
   SELECT * from Employees;
</sql:query>
 
<table border="1" width="100%">
<tr>
   <th>Emp ID</th>
   <th>First Name</th>
   <th>Last Name</th>
   <th>Age</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
   <td><c:out value="${row.id}"/></td>
   <td><c:out value="${row.first}"/></td>
   <td><c:out value="${row.last}"/></td>
   <td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>
 
</body>
</html>
 
 

Sending XML from a JSP

To send XML data as a page back to client, set the content type of your page to text/xml.
<%@ page contentType="text/xml" %>
Full code:
<%@ page contentType="text/xml" %>
<books>
   <book>
      <name>JSP</name>
      <author>java2s.com</author>
      <price>123</price>
   </book>
</books>
 
 

Parse XML in JSP

To parse XML using JSP, install the following two XML and XPath libraries into your <Tomcat Installation Directory>\lib:
First, create the books.xml file as follows:
<books>
<book>
  <name>JSP</name>
  <author>java2s.com</author>
</book>
<book>
  <name>Servlet</name>
  <author>java2s.com</author>
</book>
</books>
Create the following main.jsp in the same folder with the above xml file.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
 
<html>
<body>
<c:import var="bookInfo" url="http://localhost:8080/books.xml"/>
<x:parse xml="${bookInfo}" var="output"/>
<b>The title of the first book is</b>: 
<x:out select="$output/books/book[1]/name" />
</body>
</html>
Access above JSP using http://localhost:8080/main.jsp.
 
 

Format/Transform XML in JSP with XSLT

First, create the following XSLT stylesheet style.xsl:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl=
"http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
  <html>
  <body>
   <xsl:apply-templates/>
  </body>
  </html>
</xsl:template>
<xsl:template match="books">
  <table border="1" width="100%">
    <xsl:for-each select="book">
      <tr>
        <td>
          <i><xsl:value-of select="name"/></i>
        </td>
        <td>
          <xsl:value-of select="author"/>
        </td>
        <td>
          <xsl:value-of select="price"/>
        </td>
      </tr>
    </xsl:for-each>
  </table>
</xsl:template>
</xsl:stylesheet>
Apply the above style sheet within JSP file.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<body>
<c:set var="xmltext">
  <books>
    <book>
      <name>JSP</name>
      <author>java2s.com</author>
      <price>100</price>
    </book>
    <book>
      <name>Servlet</name>
      <author>java2s.com</author>
      <price>2000</price>
    </book>
  </books>
</c:set>
 
<c:import url="http://localhost:8080/style.xsl" var="xslt"/>
<x:transform xml="${xmltext}" xslt="${xslt}"/>
 
</body>
</html>
 
 
A JavaBean is Java code following the JavaBeans API specifications.
A JavaBean has the following features.
  • It has a default, no-argument constructor.
  • It should implement the Serializable interface.
  • It has a list of properties for reading or writing.
  • It has a list of getter and setter methods for the properties.
The following code shows how to create a Student JavaBean.
The firstName, lastName and age are all properties. And each property has a getter method and a setter method.
For example, the getter method for firstName is getFirstName, it is created by uppercase the first letter of the property and append get to the front.
We can use the same way to create setter methods.
package com.java2s;

public class StudentsBean implements java.io.Serializable
{
   private String firstName = null;
   private String lastName = null;
   private int age = 0;

   public StudentsBean() {
   }
   public String getFirstName(){
      return firstName;
   }
   public String getLastName(){
      return lastName;
   }
   public int getAge(){
      return age;
   }
   public void setFirstName(String firstName){
      this.firstName = firstName;
   }
   public void setLastName(String lastName){
      this.lastName = lastName;
   }
   public void setAge(Integer age){
      this.age = age;
   }
}
 
 
 

Example

The useBean action declares a JavaBean in a JSP. The syntax for the useBean tag is as follows:
<jsp:useBean id="bean's name" scope="bean's scope" typeSpec/>
The scope attribute could be page, request, session or application.
The id attribute should be a unique name among other useBean declarations in the same JSP.
The following code shows how to use java Date bean.
<html>
<body>
<jsp:useBean id="date" class="java.util.Date" /> 
<p>The date/time is <%= date %>

</body>
</html>
To get JavaBean property, use <jsp:getProperty/> action. To set JavaBean property, use <jsp:setProperty/> action.
<jsp:useBean id="id" class="bean's class" scope="bean's scope">
   <jsp:setProperty name="bean's id" property="property name"  
                    value="value"/>
   <jsp:getProperty name="bean's id" property="property name"/>
   ...........
</jsp:useBean>
The following code shows how to get and set the StudentBean's properties.
<html>
<body>
<jsp:useBean id="students" class="com.java2s.StudentsBean"> 
   <jsp:setProperty name="students" property="firstName" value="Jack"/>
   <jsp:setProperty name="students" property="lastName" value="Smith"/>
   <jsp:setProperty name="students" property="age" value="24"/>
</jsp:useBean>

<p>Student First Name: <jsp:getProperty name="students" property="firstName"/>
</p>
<p>Student Last Name: <jsp:getProperty name="students" property="lastName"/>
</p>
<p>Student Age: <jsp:getProperty name="students" property="age"/>
</p>

</body>
</html>
Save StudentsBean.class available in CLASSPATH.
 
 
JSP page are built from tags and other than the existing tags in the standard tag library we can create custom tag. A custom tag is a user-defined JSP language element.
We use the Simple Tag Handlers to write the custom tags.
To create a customer tag, extend SimpleTagSupport class and override the doTag() method. Inside the doTag() method, we can add our code to generate content for the tag.

Example

The following code shows how to create a tag to output static string.
We call the new tag My.
After creating the tag, we can use it as follows.
<ex:My />
First, create MyTag.java as follows:
package com.java2s;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;

public class MyTag extends SimpleTagSupport {

  public void doTag() throws JspException, IOException {
    JspWriter out = getJspContext().getOut();
    out.println("My Custom Tag!");
  }
}
Second, create following tag library file as in< Tomcat-Installation-Directory>webapps\ROOT\WEB-INF\custom.tld.
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <short-name>Example TLD</short-name>
  <tag>
    <name>My</name>
    <tag-class>com.java2s.MyTag</tag-class>
    <body-content>empty</body-content>
  </tag>
</taglib>
Use above defined custom tag My in our JSP program as follows:
<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
<html>
  <head>
    <title>A sample custom tag</title>
  </head>
  <body>
    <ex:My/>
  </body>
</html>
 
 
 

Access the Tag Body

You can include a message in the tag body. The following code shows how to add tag body to a custom tag.
<ex:My>
   This is message body
</ex:My>
The following code shows how to access the body text in Java code.
package com.java2s;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;

public class MyTag extends SimpleTagSupport {

   StringWriter sw = new StringWriter();
   public void doTag() throws JspException, IOException{
       getJspBody().invoke(sw);
       getJspContext().getOut().println(sw.toString());
    }
}
Add the custom tag to the tag declaration TLD file as follows:
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <short-name>Example TLD with Body</short-name>
  <tag>
    <name>My</name>
    <tag-class>com.java2s.MyTag</tag-class>
    <body-content>scriptless</body-content>
  </tag>
</taglib>
Now let us call above tag with proper body as follows:
<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
<html>
  <body>
    <ex:My>
        This is message body
    </ex:My>
  </body>
</html>
 
 

Custom Tag Attributes

To use an attribute value, a custom tag class needs to implement setter methods, in the same way as a JavaBean.
package com.java2s;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;

public class MyTag extends SimpleTagSupport {

   private String message;

   public void setMessage(String msg) {
      this.message = msg;
   }
   public void doTag() throws JspException, IOException
    {
       if (message != null) {
          JspWriter out = getJspContext().getOut();
          out.println( message );
       }else{
          getJspContext().getOut().println("no message");
       }
   }

}
 

Example 2

The following code shows how to add this attribute in TLD file using <attribute> element.
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>2.0</jsp-version>
  <short-name>Example TLD with Body</short-name>
  <tag>
    <name>My</name>
    <tag-class>com.java2s.MyTag</tag-class>
    <body-content>scriptless</body-content>
    <attribute>
       <name>message</name>
    </attribute>
  </tag>
</taglib>
Now let us try following JSP with message attribute as follows:
<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
<html>
  <head>
    <title>A sample custom tag</title>
  </head>
  <body>
    <ex:My message="This is custom tag" />
  </body>
</html>
We can set the following properties for an attribute:
Property Purpose
namedefines the name of an attribute. Each attribute name must be unique for a particular tag.
requiredspecifies if this attribute is required. It would be false for optional.
rtexprvalueif a runtime expression value for a tag attribute is valid
typeDefines the Java class-type of this attribute. By default it is String.
descriptionInformational description can be provided.
fragmentDeclares if this attribute value should be treated as a JspFragment.

Example 3

For example, the following code shows how to specify properties related to an attribute:
    ...
    <attribute>
      <name>attribute_name</name>
      <required>false</required>
      <type>java.util.Date</type>
      <fragment>false</fragment>
    </attribute>
    ...
We can set two attributes in TLD file as follows:
.....
    <attribute>
      <name>attribute_name1</name>
      <required>false</required>
      <type>java.util.Boolean</type>
      <fragment>false</fragment>
    </attribute>
    <attribute>
      <name>attribute_name2</name>
      <required>true</required>
      <type>java.util.Date</type>
    </attribute>
.....
 
 
 
JSP Expression Language, or JSP EL, can easily access data stored in JavaBeans components.  
JSP EL can create arithmetic and logical expressions. 
Inside a JSP EL expression, we can use numbers, strings, boolean values, and null.
The following code shows how to use a string to set an attribute value in a JSP tag.
<jsp:setProperty name="box" property="height" value="100"/>
value="100" sets the constant value 100 to box's height property.
With JSP EL we can put an expression in the value attribute for jsp:setProperty in the following syntax.
${expr}
expr specifies the expression.
The following code uses the JSP EL to in <jsp:setProperty> tag to double the width as the height.
<jsp:setProperty name="box" property="height" 
                 value="${2*box.width}"/>
You can use JSP EL expressions within template text for a tag. The following <jsp:text> declaration inserts <h1>Hello JSP!</h1> into the JSP output:
<jsp:text>
<h1>Hello JSP!</h1>
</jsp:text>
You can include a JSP EL expression in the body of a <jsp:text> tag or any other tag. For example:
<jsp:text>
Box heightis: ${2*box.width}
</jsp:text>
To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page directive as below:
<%@ page isELIgnored ="true|false" %>
 
 

Operators in EL

JSP Expression Language supports most of the arithmetic and logical operators supported by Java.
OperatorDescription
. Access a bean property
[] Access an array or List element
( ) Group a expression to change the evaluation order
+ Add
- Subtract
* Multiply
/ or div Division
% or mod Modulo
== or eq equality
!= or ne Not equality
< or lt less than
> or gtgreater than
<= or le less than or equal
>= or gt greater than or equal
&& or and logical AND
|| or or logical OR
! or not Unary Boolean complement
empty Test for empty variable values
 
 
 
 
 

Functions in JSP Expression Language

We can define functions in JSP EL with the following syntax:
${ns:func(param1, param2, ...)}
ns is the namespace of the function, func is the name of the function and param1 is the first parameter value.
For example, the function fn:length, which is part of the JSTL library can be used as follows to get the the length of a string.
${fn:length("hello")}
To use a function from tag libraries, install the libraries on your server and include the libraries in your JSP using <taglib> directive.

JSP Expression Language Implicit Objects

The JSP expression language supports the following implicit objects:
Implicit objectDescription
pageScopepage scoped variables
requestScoperequest scoped variables
sessionScopesession scoped variables
applicationScopeapplication scoped variables
paramRequest parameters as strings
paramValuesRequest parameters as collections of strings
headerHTTP request headers as strings
headerValuesHTTP request headers as collections of strings
initParamContext-initialization parameters
cookieCookie values
pageContextThe JSP PageContext object for the current page
The pageContext object can access pageContext JSP object. For example, to access the incoming query string for a request, use the expression:
${pageContext.request.queryString}
To explicitly access the aVariable variable in the application scope, access it through the applicationScope variable as applicationScope.aVariable.
The param and paramValues objects can access the parameter values available through the request.getParameter and request.getParameterValues methods.
To access a parameter named myVariable, use the expression ${param.myVariable} or ${param["myVariable"]}.
The following code shows how to access a request parameter named myVariable:
<%@ page import="java.io.*,java.util.*" %>
<%
    String title = "Accessing Request Param";
%>
<html>
<body>
<h1><% out.print(title); %></h1>
<p>${param["myVariable"]}</p>
</body>
</html>
The header and headerValues objects can access the header values available through the request.getHeader and request.getHeaders methods respectively.
To access a header named user-agent, use the expression ${header.user-agent} or ${header["user-agent"]}.
<%@ page import="java.io.*,java.util.*" %>
<html>
<body>
<p>${header["user-agent"]}</p>

</body>
</html>
 
 

Functions in JSP Expression Language

We can define functions in JSP EL with the following syntax:
${ns:func(param1, param2, ...)}
ns is the namespace of the function, func is the name of the function and param1 is the first parameter value.
For example, the function fn:length, which is part of the JSTL library can be used as follows to get the the length of a string.
${fn:length("hello")}
To use a function from tag libraries, install the libraries on your server and include the libraries in your JSP using <taglib> directive.

JSP Expression Language Implicit Objects

The JSP expression language supports the following implicit objects:
Implicit objectDescription
pageScopepage scoped variables
requestScoperequest scoped variables
sessionScopesession scoped variables
applicationScopeapplication scoped variables
paramRequest parameters as strings
paramValuesRequest parameters as collections of strings
headerHTTP request headers as strings
headerValuesHTTP request headers as collections of strings
initParamContext-initialization parameters
cookieCookie values
pageContextThe JSP PageContext object for the current page
The pageContext object can access pageContext JSP object. For example, to access the incoming query string for a request, use the expression:
${pageContext.request.queryString}
To explicitly access the aVariable variable in the application scope, access it through the applicationScope variable as applicationScope.aVariable.
The param and paramValues objects can access the parameter values available through the request.getParameter and request.getParameterValues methods.
To access a parameter named myVariable, use the expression ${param.myVariable} or ${param["myVariable"]}.
The following code shows how to access a request parameter named myVariable:
<%@ page import="java.io.*,java.util.*" %>
<%
    String title = "Accessing Request Param";
%>
<html>
<body>
<h1><% out.print(title); %></h1>
<p>${param["myVariable"]}</p>
</body>
</html>
The header and headerValues objects can access the header values available through the request.getHeader and request.getHeaders methods respectively.
To access a header named user-agent, use the expression ${header.user-agent} or ${header["user-agent"]}.
<%@ page import="java.io.*,java.util.*" %>
<html>
<body>
<p>${header["user-agent"]}</p>

</body>
</html>

Example

The following code is for ShowError.jsp which includes the directive <%@ page isErrorPage="true" %>. This directive generates the exception instance variable.
<%@ page isErrorPage="true" %>
<html>
<body>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>
 
 

Example 2

The following code shows how to output exception information using JSP expression language.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isErrorPage="true" %>
<html>
<body>
    <b>Error:</b>${pageContext.exception}
    <b>URI:</b>${pageContext.errorData.requestURI}
    <b>Status code:</b>${pageContext.errorData.statusCode}
    <c:forEach var="trace" items="${pageContext.exception.stackTrace}">
        <p>${trace}</p>
    </c:forEach>
</body>
</html>
 
 

Languages Setting

We can change the JSP page language settings by setting Content-Language header.
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%
    // Set response content type
    response.setContentType("text/html");
    // Set spanish language code.
    response.setHeader("Content-Language", "es");
    String title = "En Espaol";

%>
<html>
<body>
<h1><%  out.print(title); %></h1>
</body>
</html>
 
 

Locale Specific Dates

The following code shows how to use request locale and java.text.DateFormat class to format date and time specific to a locale.
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%@ page import="java.text.DateFormat,java.util.Date" %>

<%
    String title = "Locale Specific Dates";
    //Get the client's Locale
    Locale locale = request.getLocale( );
    String date = DateFormat.getDateTimeInstance(
                                  DateFormat.FULL, 
                                  DateFormat.SHORT, 
                                  locale).format(new Date( ));
%>
<html>
<body>
<h1><% out.print(title); %></h1>
<p>Local Date: <%  out.print(date); %></p>
</body>
</html>
 
 

Locale Specific Currency

The following code shows how to use java.txt.NumberFormat class to format a number specific to a given locale:
<%@ page import="java.io.*,java.util.Locale" %>
<%@ page import="javax.servlet.*,javax.servlet.http.* "%>
<%@ page import="java.text.NumberFormat,java.util.Date" %>

<%
    String title = "Locale Specific Currency";
    //Get the client's Locale
    Locale locale = request.getLocale( );
    NumberFormat nft = NumberFormat.getCurrencyInstance(locale);
    String formattedCurr = nft.format(1000000);
%>
<html>
<body>
<center>
<h1><% out.print(title); %></h1>
</center>
<div align="center">
<p>Formatted Currency: <%  out.print(formattedCurr); %></p>
</div>
</body>
</html>
 
 
 
 

No comments:

Post a Comment