Introduction to JSP
- What is JSP?
- Differences between servlets and JSP
- JSP Steps for transforming into Servlet
- JSP Life Cycle
- Components of JSP
- JSP Directives
- JSP Scripting
- JSP Action Tags
- JSP Implicit Object
- Comment Style in JSP
- JSP Versions
- Examples
What is JSP? |
- JavaServer Pages (JSP) is a Java technology that helps software developers serve dynamically generated web pages based on HTML, XML, or other document types.
- Released in 1999 as Sun’s answer to ASP and PHP;
- JSP technology facilitates the segregation of the work profiles of a Web designer and a Web developer.
- A Web designer can design and formulate the layout for a Web page by using HTML.
- A Web developer, working independently, can use Java code and other JSP specific tags to code the business logic.
- Java is known for its characteristic of “write once, run anywhere”. JSP pages are platform independent. You can port your .jsp pages to any platform.
Differences between servlets and JSP |
- Servlets tie up files to independently handle the static presentation logic and the dynamic business logic.On the other hand, JSP allows Java to be embedded directly into an HTML page by using special tags.
- Servlet programming involves extensive coding. Any changes made to the code requires identification of the static code content and dynamic code content to facilitate incorporation of the changes.
On the other hand, a JSP page, by virtue of the separate placement of the static and dynamic content, facilitates both Web developers and the Web designer to work independently.
JSP Phases for transforming into Servlet |
JSPs life cycle can be grouped into following phases
1. JSP Page Translation:
- A java servlet file is generated from the JSP source file.
- This is the first step in its tedious multiple phase life cycle.
- In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files.
- The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.
2. JSP Page Compilation:
The generated java servlet file is compiled into a java servlet class.
Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.
3. Class Loading:
The java servlet class that was compiled from the JSP source is loaded into the container.
4. Execution phase:
- In the execution phase the container manages one or more instances of this class in response to requests and other events.
- The interface JspPage contains jspInit() and jspDestroy().
- The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().
5. Initialization:
- jspInit() method is called immediately after the instance was created.
- It is called only once during JSP life cycle.
6. _jspService() execution:
- This method is called for every request of this JSP during its life cycle.
- This is where it serves the purpose of creation.
- Oops! it has to pass through all the above steps to reach this phase.
- It passes the request and the response objects. _jspService() cannot be overridden.
7. jspDestroy() execution:
- This method is called when this JSP is destroyed.
- With this call the servlet serves its purpose and submits itself to heaven (garbage collection).
- This is the end of jsp life cycle.
Note:- jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.
JSP Life Cycle |
JSP life cycle methods are:
- jspInit() :- Is invoked at the time when the servlet is initialized.
- jspService() :- Is invoked when request for the JSP page is received.
- jspDestroy() :- Is invoked before the servlet is removed from the service.
Components of JSP |
The three components of a JSP page are:
- JSP directives
- JSP scripting
- JSP action tags
JSP Directives |
A directive element in a JSP page provides global information about a particular JSP page and is of three types:
- page Directivec
- taglib Directive
- include Directive
The syntax for defining a directive is:
<%@ directive attribute=value %>
The page Directive :
- Defines attributes that notify the Web container about the general settings of a JSP page.
- The page directive does not apply to any dynamic resources.
- You can use the page directive more than once in a translation unit, but you can only use each attribute, except import, once.
JSP Syntax
<%@ page attribute_list %>
<%@ page
[ <b>language</b>="java" ]
[ <b>extends</b>="package.class" ]
[ <b>import</b>="{package.class | package.*}, ..." ]
[ <b>session</b>="true|false" ]
[ <b>buffer</b>="none|8kb|sizekb" ]
[ <b>autoFlush</b>="true|false" ]
[ <b>isThreadSafe</b>="true|false" ]
[ <b>info</b>="text" ]
[ <b>errorPage</b>="relativeURL" ]
[ <b>contentType</b>="mimeType [ ; charset=characterSet ]" |
"text/html ; charset=ISO-8859-1" ]
[ <b>isErrorPage</b>="true|false" ]
[ <b>pageEncoding</b>="characterSet | ISO-8859-1" ]
%>
XML Syntax
<jsp:directive.page pageDirectiveAttrList />
Examples
<%@ page import="java.util.*, java.sql.*" %>
<%@ page buffer="5kb" autoFlush="false" %>
<jsp:directive.page errorPage="error.jsp" />
Attributes
language=”java”
The scripting language used in scriptlets, declarations, and expressions in the JSP page and any included files. In v1.2, the only allowed value is java.
extends=”package.class”
The fully qualified name of the superclass of the Java class this JSP page will be compiled to. Use this attribute cautiously, as it can limit the JSP container’s ability to provide a specialized superclass that improves the quality of the compiled class.
import=”{package.class | package.*}, …”
A comma-separated list of Java packages that the JSP page should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP page. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP page.
The following packages are implicitly imported, so you don’t need to specify them with the import attribute:
java.lang.* , javax.servlet.* , javax.servlet.jsp.*, javax.servlet.http.*
You must place the import attribute before the element that calls the imported class.
session=”true|false”
Whether the client must join an HTTP session in order to use the JSP page. If the value is true, the session object refers to the current or new session.
If the value is false, you cannot use the session object or a <jsp:useBean> element with scope=session in the JSP page. Either of these usages would cause a translation-time error.
The default value is true.
buffer=”none|8kb|sizekb”
The buffer size in kilobytes used by the out object to handle output sent from the compiled JSP page to the client web browser. The default value is 8kb. If you specify a buffer size, the output is buffered with at least the size you specified.
autoFlush=”true|false”
Whether the buffered output should be flushed automatically when the buffer is full. If set to true (the default value), the buffer will be flushed. If set to false, an exception will be raised when the buffer overflows. You cannot set autoFlush to false when buffer is set to none.
isThreadSafe=”true|false”
Whether thread safety is implemented in the JSP page. The default value is true, which means that the JSP container can send multiple, concurrent client requests to the JSP page. You must write code in the JSP page to synchronize the multiple client threads. If you use false, the JSP container sends client requests one at a time to the JSP page.
info=”text”
A text string that is incorporated verbatim into the compiled JSP page. You can later retrieve the string with the Servlet.getServletInfo() method.
errorPage=”relativeURL”
A pathname to a JSP page that this JSP page sends exceptions to.
isErrorPage=”true|false”
Whether the JSP page displays an error page. If set to true, you can use the exception object in the JSP page. If set to false (the default value), you cannot use the exception object in the JSP page.
contentType=”mimeType [; charset=characterSet ]” | “text/html; charset=ISO-8859-1”
The MIME type and character encoding the JSP page uses for the response. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.
pageEncoding=”characterSet | ISO-8859-1″
The page source character encoding. The default character encoding is ISO-8859-1.
The include Directive
- Specifies the names of the files to be inserted during the compilation of the JSP page.
- Creates the contents of the included files as part of the JSP page.
- Inserts a part of the code that is common to multiple pages.
- It include the file during compilation of JSP into Servlet.
- If you are including a text file and do not want the text to be displayed in the JSP page, place the text in a comment element.
JSP Syntax
<%@ include file = relativeURL %>
Example
<%@ include file = "header.jsp" %>
<%@ include file = "footer.jsp" %>
The taglib Directive
- Imports a custom tag into the current JSP page.
- Associates itself with a URI to uniquely identify a custom tag.
- Associates a tag prefix string that distinguishes a custom tag with the other tag library used in a JSP page.
- The taglib directive declares that the JSP page uses custom tags, names the tag library that defines them, and specifies their tag prefix.
- You must use a taglib directive before you use the custom tag in a JSP page.
- You can use more than one taglib directive in a JSP page, but the prefix defined in each must be unique.
JSP Syntax
<%@ taglib uri=tag_lib_URI prefix=prefix %>
Example
<%@ taglib uri=hello.tld prefix=x %>
<x:DispCust>James</x:DispCust>
JSP Scripting |
JSP Scripting Elements
- Embed Java code directly into an HTML page.
- Include various scripting elements, and are as follows :
- Declarations : <%! — statement — %>
- Expressions : <%= — expr — %>
- Scriptlets : <% — java code — %>
Declaration
- Provide a mechanism to define variables and methods. Declarative statements are placed within <%! and %> symbols and always end with a semicolon.
- Declares a variable or method valid in the scripting language used in the JSP page.
JSP Syntax
<%! declaration; [ declaration; ]+ ... %>
XML Syntax
<jsp:declaration>
declaration; [ declaration; ]+ ...
</jsp:declaration>
Example
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Rect a = new Rect(2,5); %>
<%! public int add(int x,int y){ return x+y; %>
<%!
private BookDBEJB bookDBEJB;
public void jspInit() {
.....
}
public void jspDestroy() {
.....
}
%>
Expressions
Contains an expression valid in the scripting language used in the page.
Insert values directly into the output.
An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted into the response where the expression appears in the JSP page.
When the Java programming language is the scripting language you do not use a semicolon to end the expression.
It is used as out.println();
JSP Syntax
<%= expression%>
XML Syntax
<jsp:expression>
expression
</jsp:expression>
Example
String str="James";
Your Name is <font color="blue"><%= str %></font>
<%
Date d=new Date();
%>
Todays date is :
<b>
<jsp:expression>d</jsp:expression></b>.
Scriptlets
- Contains a code fragment valid in the scripting language used in the page.
- Use any of the implicit objects or any object declared with a <jsp:useBean> element.
- Scriptlets are executed at request time, when the JSP container processes the request.
- If the scriptlet produces output, the output is stored in the out object.
- Consists of valid Java code snippets that are enclosed within <% and %> symbols.
JSP Syntax
<% Java code %>
XML Syntax
<jsp:scriptlet>
Java code fragment
</jsp:scriptlet>
Example
<%
String name = null;
if (request.getParameter("username") == null)
{
out.println("You are not authorized user");
}
else
{
out.println("You are logged in successfully");
}
%>
JSP Action Tags |
JSP Actions
Perform tasks, such as insertion of files, reusing beans, forwarding a user to another page, and instantiating objects.
The syntax to use a JSP action in a JSP page is
<jsp:attribute>
<jsp:useBean>
- Instantiates or references a bean with a specific name and scope.
- The <jsp:useBean> element locates or instantiates a JavaBeans component.
- <jsp:useBean> first attempts to locate an instance of the bean.
- If the bean does not exist, <jsp:useBean> instantiates it from a class or serialized template.
JSP Syntax
<jsp:useBean class="nbeanInstanceName" scope="page|request|session|application"
{
class="package.class" [ type="package.class" ]| beanName="{package.class | <%=expression %>}"
type="package.class" | type="package.class"
}
{ /> | > other elements </jsp:useBean> }
Example
<jsp:useBean class="nobj" scope="page" class="pack.Student" />
<jsp:setProperty name="obj" property="*" />
OR
<jsp:useBean class="nobj" scope="page" class="pack.Student" >
<jsp:setProperty name="obj" property="sname" value="JamesBond" />
<jsp:setProperty name="obj" property="sid" value="121" />
</jsp:useBean>
scope="page | request | session | application"
The scope in which the bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:
page :
You can use the bean within the JSP page with the <jsp:useBean> element or any of the page’s static include files, until the page sends a response back to the client or forwards a request to another resource.
request :
You can use the bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another resource. You can use the request object to access the bean, for example, request.getAttribute(beanInstanceName).
session :
You can use the bean from any JSP page in the same session as the JSP page that created the bean. The bean exists across the entire session, and any page that participates in the session can use it. The page in which you create the bean must have a page directive with session=”true”.
application :
You can use the bean from any JSP page in the same application as the JSP page that created the bean. The bean exists across an entire JSP application, and any page in the application can use the bean.
<jsp:setProperty>
Sets a bean property value or values.
JSP Syntax
<jsp:setProperty name="beanInstanceName"
{
property="*" |
property="propertyName" [ param="parameterName" ] |
property="propertyName" value="{stringLiteral| <%= expression %>}"
}
/>
Example
<jsp:setProperty name="obj" property="*" />
<jsp:setProperty name="obj" property="sname" />
<jsp:setProperty name="obj" property="sname" value="JamesBond" />
Note:- [ property=”*” ] :- Stores all of the values of request parameters in bean properties. The names of the bean properties must match the names of the request parameters
<jsp:getProperty>
Inserts the value of a bean property into the response.
JSP Syntax
<jsp:getProperty name="beanInstanceName" property="propertyName" />
Example
<jsp:useBean class="nobj" scope="page" class="pack.Student" />
<h2>
Student Name is : <jsp:getProperty name="obj" property="sname" />
</h2>
<jsp:include>
Includes a static resource or the result from another web component
JSP Syntax
<jsp:include page="{relativeURL | <%= expression %>}" flush="true| false" />
or
<jsp:include page="{relativeURL | <%= expression %>}" flush="true| false" >
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+
</jsp:include>
Example
<jsp:include page="scripts/login.jsp" />
<jsp:include page="copyright.html" />
<jsp:include page="/index.html" />
<jsp:include page="scripts/login.jsp">
<jsp:param name="username" value="jsmith" />
</jsp:include>
Note:- The <jsp:include> element allows you to include either a static or dynamic resource in a JSP page. The results of including static and dynamic resources are quite different. If the resource is static, its content is included in the calling JSP page. If the resource is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing the remainder of the JSP page.
<jsp:forward>
Forwards a request to an HTML file, JSP page, or servlet.
JSP Syntax
<jsp:forward page="{relativeURL | <%= expression %>}" />
OR
<jsp:forward page="{relativeURL | <%= expression %>}" >
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /> +
</jsp:forward>
Example
<jsp:forward page="/loginservlet?user=james" />
OR
<jsp:forward page="/loginservlet">
<jsp:param name="username" value="JamesBond" />
</jsp:forward>
<jsp:param>
Defines a parameter to be passed to an included or forwarded page.
<jsp:plugin>
- Causes the execution of an applet or bean. The applet or bean executes in the specified plugin.
- If the plugin is not available, the client displays a dialog to initiate the download of the plugin software.
JSP Syntax
<jsp:plugin
type="bean|applet"
code="classFileName"
codebase="classFileDirectoryName"
[ name="instanceName" ]
[ archive="URIToArchive, ..." ]
[ align="bottom|top|middle|left|right" ]
[ height="{displayPixels | <%= expression %>}"]
[ width="{displayPixels | <%= expression %>}"]
[ hspace="leftRightPixels" ]
[ vspace="topBottomPixels" ]
[ jreversion="JREVersionNumber | 1.2" ]
[ nspluginurl="URLToPlugin" ]
[ iepluginurl="URLToPlugin" ] >
[ <jsp:params>
[ <jsp:param name="parameterName"
value="{parameterValue | <%= expression %>}" /> ]+
</jsp:params> ]
[ <jsp:fallback> text message for user </jsp:fallback> ]
</jsp:plugin>
Example
<jsp:plugin type=applet code="Student.class" codebase="/html">
<jsp:params>
<jsp:param name="xx" value="s001" />
</jsp:params>
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>
</jsp:plugin>
JSP Implicit Object |
JSP Implicit Objects are:
- Pre-defined variables that can be included in JSP expressions and scriptlets.
- Implemented from servlet classes and interfaces.
List of Implicit Objects
Variable | Class/Interface | Description |
---|---|---|
application | javax.servlet.ServletContext | The context for the JSP page’s servlet and any Web components contained in the same application. |
config | javax.servlet.ServletConfig | Initialization information for the JSP page’s servlet. |
exception | java.lang.Throwable | Accessible only from an error page. for Handling Errors in JSP page. |
out | javax.servlet.jsp.JspWriter | The output stream. |
page | java.lang.Object | The instance of the JSP page’s servlet processing the current request. Not typically used by JSP page authors. |
pageContext | javax.servlet.jsp.PageContext | The context for the JSP page. Provides a single API to manage the various scoped attributes described in Sharing Information.This API is used extensively when implementing tag handlers. |
request | Subtype of javax.servlet.ServletRequest | The request triggering the execution of the JSP page. See Getting Information from Requests. |
response | Subtype of javax.servlet.ServletResponse | The response to be returned to the client. Not typically used by JSP page authors. |
session | javax.servlet.http.HttpSession | The session object for the client. |
Comment Style in JSP |
Documents the JSP page but is not inserted into the response.
JSP Syntax
<%– comment –%>
Example:
<%@ page language="java" %>
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<font color="#FFFF00"><span style="background-color: #008000"><%-- This comment will not be inclueded in the response --%>
</span></font></body>
</html>
JSP Versions |
- JSP 1.1 and 1.0
- JSP 1.2 with Servlet 2.3 specifications
- JSP 2.0
- JSP 2.1 as part of Java EE 5
- JSP 2.2 specification has been released as a maintenance of JSP 2.1
JSP 2.0
- The new version of the JSP specification includes new features meant to improve programmer productivity. Namely:
- An Expression Language (EL) which allows developers to create Velocity-style templates (among other things).
- A faster/easier way to display parameter values.
- A clear way to navigate nested beans.
- The Java EE 5 Platform has focused on easing development by making use of Java language annotations that were introduced by J2SE 5.0. JSP 2.1 supports this goal by defining annotations for dependency injection on JSP tag handlers and context listeners.
- Another key concern of the Java EE 5 specification has been the alignment of its web tier technologies, namely JavaServer Pages (JSP), JavaServer Faces (JSF), and the JavaServer Pages Standard Tag Library (JSTL).
- The outcome of this effort has been the Unified Expression Language (EL), which integrates the expression languages defined by JSP 2.0 and JSF 1.1.
- Thanks to the Unified EL, JSTL tags, such as the JSTL iteration tags, can now be used with JSF components in an intuitive way.
Write following code to know the version supported for servlet and jsp by servers
test.jsp
Server info:
<%=application.getServerInfo()%><br>
Servlet version:<%=application.getMajorVersion()%>.<%=application.getMinorVersion()%><br>
JSP version:<%=JspFactory.getDefaultFactory().getEngineInfo().getSpecificationVersion()%><br>
Java version:<%=System.getProperty("java.version")%><br>
Now Access page using url “http://localhost:8080/test.jsp” and u will find following output in browser
On Tomcat 5.5 , Support of Servlet and JSP Version as below
Server info: Apache Tomcat/5.5.35
Servlet version:2.4
JSP version:2.0
Java version:1.7.0_03
On Tomcat 6.0 , Support of Servlet and JSP Version as below
Server info: Apache Tomcat/6.0.29
Servlet Specification: 2.5
JSP version: 2.1
Java version:1.7.0_03
On Tomcat 7.0 , Support of Servlet and JSP Version as below
Server info: Apache Tomcat/7.0.11
Servlet Specification: 3.0
JSP version: 2.1
Java version:1.7.0_03
Examples |
1. Displaying date using JSP
2. Calculator Using JSP
3. Storing Customer using JSP
4. Retrieving Customer using JSP
5. Login page validating thru JSP
6. Generating Error Page using JSP
7. Displaying State list on the selection of Country from list [ using Database ]
Recent Comments