0% found this document useful (0 votes)
10 views

Java Server Pages Notess

Easy to understand

Uploaded by

xtremechalak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java Server Pages Notess

Easy to understand

Uploaded by

xtremechalak
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

JSP(Java Server Page)

Java Server Pages (JSP) is a technology for developing web pages that support dynamic content which
helps developers insert java code in HTML pages by making use of special JSP tags, most of which start
with <% and end with %>.

 A Java Server Pages component is a type of Java servlet that is designed to


fulfill the role of a user interface for a Java web application.

 Web developers write JSPs as text files that combine HTML or XHTML code,
XML elements, and embedded JSP actions and commands.

 Using JSP, you can collect input from users through web page forms,
present records from a database or another source, and create web pages
dynamically.

 JSP tags can be used for a variety of purposes, such as retrieving


information from a database or registering user preferences, accessing
JavaBeans components, passing control between pages and sharing
information between requests, pages etc

 Java Server Pages often serve the same purpose as programs implemented
using the Common Gateway Interface (CGI).

 But JSP offer several advantages in comparison with the CGI.

o Performance is significantly better because JSP allows embedding Dynamic


Elements in HTML Pages itself instead of having a separate CGI files.

 JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to servlet because it provides more
functionality than servlet such as expression language, jstl etc.

 A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to
maintain than servlet because we can separate designing and development.
It provides some additional features such as Expression Language, Custom
Tag etc.

 JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to servlet because it provides more
functionality than servlet such as expression language, jstl etc.

1
 A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to
maintain than servlet because we can separate designing and development.
It provides some additional features such as Expression Language, Custom
Tag etc.

Advantage of JSP over Servlet


There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of
servlet in JSP. In addition to, we can use implicit objects, predefined tags,
expression language and Custom tags in JSP that makes JSP development easy.

2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In servlet technology, we mix our business logic with the
presentation logic.

3) Fast Development: No need to recompile and redeploy


If JSP page is modified, we don't need to recompile and redeploy the project. The
servlet code needs to be updated and recompiled if we have to change the look
and feel of the application.
4) Less code than Servlet
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that
reduces the code. Moreover, we can use EL, implicit objects etc.

Life Cycle of JSP


 A JSP life cycle can be defined as the entire process from its creation till the
destruction which is similar to a servlet life cycle with an additional
stepwhich is required to compile a JSP into servlet.

2
 The following are the paths followed by a JSP
o Compilation
o Initialization
o Execution
o Cleanup

3
JSP Compilation:

 When a browser asks for a JSP, 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.
 The compilation process involves three steps:
 Parsing the JSP.
 Turning the JSP into a servlet.
 Compiling the servlet.
JSP Initialization:
 When a container loads a JSP it invokes the jspInit() method before servicing
any requests.
 If you need to perform JSP-specific initialization, override the jspInit()
method:
public void jspInit()
{
// Initialization code...
}
JSP Execution:
 This phase of the JSP life cycle represents all interactions with requests until
the JSP is destroyed.
 Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the JSP.
 The _jspService() method takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows:
 void _jspService(HttpServletRequest request, HttpServletResponse response)
{ // Service handling code... }
JSP Cleanup:
 The destruction phase of the JSP life cycle represents when a JSP is being
removed from use by a container.
 The jspDestroy() method is the JSP equivalent of the destroy method for
servlets.
 Override jspDestroy when you need to perform any cleanup, such as
releasing database connections or closing open files.
public void jspDestroy()
{
// Your cleanup code goes here.
}

4
JSP Document
The JSP specification supports two basic styles of delimiting its scripting elements:
 JSP pages
 JSP documents
This means a JSP page can now use either traditional JSP style syntax or XML style
JSP syntax within its source file.

JSP pages use the traditional or shorthand syntax, whereas JSP documents are
completely XML-compliant. JSP documents are also referred to as JSP pages XML
syntax.

Following are the advantages of using a JSP Document:


 JSP documents can be easily verified as well-formed XML/HTML.
 JSP documents can be validated against an XML Schema.
 JSP documents can be readily written and parsed using standard XML tools.
 JSP documents can be written and presented in alternate forms using
XSLT[eXtensibleStylesheet Language Transforamations].
 JSP uses XML compliant include and forward actions as well as custom tags.
This makes the entire document XML-compliant, which in turn leads to
increased code consistency.
 JSP documents require slightly more developer discipline than JSP pages. This
makes the code spec more readable and maintainable, especially for those to
whom JSP is new.

Converting a JSP page into a JSP document is very simple and straightforward.

JSP elements
Java code cannot be written anywhere in the page. The JSP translator needs to be
informed, which bits of code is Java and which bits of code is regular HTML. To do
this, the JSP specification provides HTML elements. These elements enclose the
Java code spec in a JSP page and are categorized as follows:
 Directives
 Scripting Elements
 Action Elements

Directives
JSP directives serve special processing information about the page to the JSP
server. JSP directives are used to:
 Set global values such as class declaration.
5
 Methods to be implemented.
 The scripting language for the page and so on.

The y do not produce any output that is visible to the They are typically used to
provide a direction to the JSP server processing the page.

Note: JSP directives affect only the JSP file that holds it.
Following are the directives available in JSP:
1).The page directive.
2). Theinclude directive
3). Thetaglib directive

1).The page directive


The page directive allows importing classes, customizing the Servlet superclass,
setting the content type and so on. A page directive can be placed anywhere the
document.

The page directive supports several attributes that affect the whole page. A single JSP page can
contain multiple page directives. During the translation, all page directives are assimilated and
applied together to the same page along with any of its static include files. The page directive
does not apply to any dynamic include files.

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive


<%@ page attribute="value" %>

Attributes of JSP page directive


 import
 contentType
 extends
 info
 buffer
 language
 isELIgnored
 isThreadSafe
 autoFlush
 session
 pageEncoding
 errorPage
 isErrorPage

6
1) import
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.

This attribute can be specified multiple times within a JSP file to import different packages.

Syntax:[In a regular JSP page]


<%@page import=”java.io.*,java.util.*”%>

2)contentType
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".

3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.

4)info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.

5)buffer
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.

6)language
The language attribute specifies the scripting language used in the JSP page. The default value is
"java".

7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its
value is false i.e. Expression Language is enabled by default.
<%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe
Servlet and JSP both are multithreaded. If you want to control this behaviour of JSP page, you can
use isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it
false, the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes
responding to a request before passing another request to it.If you make the value of
isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:
public class SimplePage_jsp extends HttpJspBase implements SingleThreadModel
{
.......
7
}

9)errorPage
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.
Example of errorPage attribute
//index.jsp
<html>
<body>

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

<%= 100/0 %>

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

Example of isErrorPage attribute


//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
2). Theinclude directive
This directive allows including files at the time the JSP page is translated into a Servlet. In other
words, this directive is used to include an HTML file, JSP or Servlet file into a JSP file. The included
files are usually used for navigation, tables, headers and footers that are common to multiple
pages.

Included file should be a static file i.e. it is included into a JSP file at the time of compilation and
once the JSP file is complied any changes in the included file will not be reflected. Most JSP
engines usually keep track of the included file and recompile the JSP if it changes.

Note: There are no restrictions on the number of include directives that may appear in a single
JSP file.

Advantage of Include directive


Code Reusability

Syntax of include directive


<%@ include file="<Filename/Relative URL>" %>
8
Example of include directive
In this example, we are including the content of the header.html file. To run this example you
must create an header.html file.
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

Note: The include directive includes the original content, so the actual page size grows at runtime.

3). Thetaglib directive


A taglib is a collection of Custom tags that can be used by the page. In other words, this directive
allows the page to use Custom tags inside the JSP page. Custom tags were introduced in JSP 1.1
version. These allow developers to hide complex server side code spec from web designers.

A taglib directive in a JSP is a link to an XML document that describes a set of Custom tags. This
XML document also determines which Tag Handler class implements the action of each tag. The
XML document names the tag library[compressed file], which holds the Custom tags. The JSP
engine uses this tag library to determine what to do when it comes across tags in the JSP.

Syntax:
<%@taglib uri=”<TagLibrryURI>” prefix=”<TagPrefix>” %>

The uri Attribute


A Uniform Resource Identifier [URI] that identifies the tag library descriptor, which is used to
uniquely name the set of custom tags and inform the server what to do with the specified tags.

JSP Scriptlet tag (Scripting elements)


In JSP, java code can be written inside the jsp page using the scriptlet tag.

Scripting elements

The scripting elements provides the ability to insert java code inside the jsp. There
are three types of scripting elements:
 scriptlet tag
 expression tag
 declaration tag

JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP.


Syntax is as follows:

9
<% java source code %>

Simple Example of JSP scriptlet tag


In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

JSP expression tag

The code placed within expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print
the values of variable or method.
Syntax of JSP expression tag
<%= statement %>

Example:
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>

JSP Declaration Tag

The JSP declaration tag is used to declare fields and methods.The code written
inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.So it doesn't get memory at each request.

Syntax of JSP declaration tag


The syntax of the declaration tag is as follows:
<%! field or method declaration %>

Difference between the jspscriptlet tag and jsp declaration tag ?

Jsp Scriptlet Tag Jsp Declaration Tag

10
The jspscriptlet tag can only declare The jsp declaration tag can declare variables as
variables not methods. well as methods.

The declaration of scriptlet tag is placed The declaration of jsp declaration tag is placed
inside the _jspService() method. outside the _jspService() method.

Example:

index.jsp

1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Comments
Comments are useful especially when building and maintaining pages is of prime
importance.
Comments identify a particular block of code which otherwise is in pure HTML
language.

Syntax:
<%-- Comments --%>

JSP Action Tags (Action Elements)


There are many JSP action tags or elements. Each tag is used to perform some
specific tasks. The action tags basically are used to control the flow between pages
and to use Java Bean. JSP action tags are as follows:

 jsp:forward
 jsp:include
 jsp:useBean
 jsp:setProperty
 jsp:getProperty
 jsp:plugin
 jsp:param
 jsp:fallback

11
jsp:forward action tag
The jsp:forward action tag is used to forward the request to another resource it
may be jsp, html or another resource.

Syntax of jsp:forward action tag without parameter

1. <jsp:forward page="relativeURL | <%= expression %>" />

Syntax of jsp:forward action tag with parameter

1. <jsp:forward page="relativeURL | <%= expression %>">


2. <jsp:param name="parametername" value="parametervalue | <%=expression%>" />
3. </jsp:forward>

Example of jsp:forward action tag without parameter

index.jsp

1. <html>
2. <body>
3. <h2>this is index page</h2>
4. <jsp:forward page="printdate.jsp" />
5. </body>
6. </html>

printdate.jsp

<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

Example of jsp:forward action tag with parameter

index.jsp

1. <html>
2. <body>
3. <h2>this is index page</h2>
4. <jsp:forward page="printdate.jsp" >
5. <jsp:param name="name" value="Java Server Page" />
6. </jsp:forward>
7. </body>
8. </html>
12
printdate.jsp

<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body>
</html>

jsp:include action tag


The jsp:include action tag is used to include the content of another resource it may
be jsp, html or servlet.The jsp include action tag includes the resource at request
time so it is better for dynamic pages because there might be changes in future.

Advantage of jsp:include action tag


code reusability

Syntax of jsp:include action tag without parameter


<jsp:include page="relativeURL | <%= expression %>" />
Syntax of jsp:include action tag with parameter
1. <jsp:include page="relativeURL | <%= expression %>">
2. <jsp:param name="parametername" value="parametervalue | <%=expression%>" />
3. </jsp:include>

Example of jsp:include action tag without parameter

In this example, index.jsp file includes the content of the printdate.jsp file.

File: index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
</body>
</html>

File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>

Java Bean
A Java Bean is a java class that should follow following conventions:
 It should have a no-arg constructor.
 It should be Serializable.

13
It should provide methods to set and get the values of the properties, known as getter
and setter methods.

Why use Java Bean?


According to Java white paper, it is a reusable software component. A bean
encapsulates many objects into one object, so we can access this object from
multiple places. Moreover, it provides the easy maintenance.

jsp:useBean action tag


The jsp:useBean action tag is used to locate or instantiate a bean class. If bean
object of the Bean class is already created, it doesn't create the bean depending on
the scope. But if object of bean is not created, it instantiates the bean.
Syntax of jsp:useBean action tag
1. <jsp:useBean id= "instanceName" scope= "page | request | session | application"
2. class= "packageName.className" type= "packageName.className"
3. beanName="packageName.className | <%= expression >" >
4. </jsp:useBean>

Attributes and Usage of jsp:useBean action tag


1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be page, request, session or
application. The default scope is page.
o page: specifies that you can use this bean within the JSP page. The
default scope is page.
o request: specifies that you can use this bean from any JSP page that
processes the same request. It has wider scope than page.
o session: specifies that you can use this bean from any JSP page in the
same session whether processes the same request or not. It has wider
scope than request.
o application: specifies that you can use this bean from any JSP page in
the same application. It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean
class) but it must have no-arg or no constructor and must not be abstract.
4. type: provides the bean a data type if the bean already exists in the scope. It
is mainly used with class or beanName attribute. If you use it without class or
beanName, no bean is instantiated.
5. beanName: instantiates the bean using the java.beans.Beans.instantiate()
14
method.
package pack;
public class Calculator
{
public int cube(int n)
{
return n*n*n;
}
}

index.jsp file

<jsp:useBean id="obj" class="pack.Calculator"/>

<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>

jsp:setProperty and jsp:getProperty action tags


The setProperty and getProperty action tags are used for developing web
application with Java Bean. In web devlopment, bean class is mostly used because it
is a reusable software component that represents data.

The jsp:setProperty action tag sets a property value or values in a bean using the
setter method.

Syntax of jsp:setProperty action tag


1. <jsp:setProperty name="instanceOfBean" property= "*" |
2. property="propertyName" param="parameterName" |
3. property="propertyName" value="{ string | <%= expression %>}"
4. />

Example of jsp:setProperty action tag if you have to set all the values of
incoming request in the bean

<jsp:setProperty name="bean" property="*" />

Example of jsp:setProperty action tag if you have to set value of the


incoming specific property

2. <jsp:setProperty name="bean" property="username" />

Example of jsp:setProperty action tag if you have to set a specific value in

15
the property

3. <jsp:setProperty name="bean" property="username" value="Kumar" />


jsp:getProperty action tag

The jsp:getProperty action tag returns the value of the property.

Syntax of jsp:getProperty action tag

4. <jsp:getProperty name="instanceOfBean" property="propertyName" />


Simple example of jsp:getProperty action tag
<jsp:getProperty name="obj" property="name" />
index.html
1. <form action="process.jsp" method="post">
2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. Email:<input type="text" name="email"><br>
5. <input type="submit" value="register">
</form>
process.jsp
7. <jsp:useBean id="u" class="pack.User"></jsp:useBean>
8. <jsp:setProperty property="*" name="u"/>
9.
10.Record:<br>
11.<jsp:getProperty property="name" name="u"/><br>
12.<jsp:getProperty property="password" name="u"/><br>
13.<jsp:getProperty property="email" name="u" /><br>
User.java
1. package pack;
2. public class User
3. {
4. private String name,password,email;
5. public void setName(String name)
6. {
7. this.name=name;
8. }
9. public String getName()
10. {
16
11. return name;
12. }
13. public void setPassword(String password)
14. {
15.this.password=password;
16. }
17. public String getPassword()
18. {
19. return password;
20. }
21. public void setEmail(String email)
22. {
23.this.email=email;
24. }
25. public String getEmail()
26. {
27. return email;
28. }
}

Implicit Objects
JSP Implicit objects are created by the web container. These implicit objects are Java
objects that implement interfaces in the Servlet and JSP API. Scripting elements in a
JSP page can make use of these JSP implicit objects. There are nine (9) JSP implicit
objects available.
JSP Implicit Objects are as follows:

1. request implicit object

The JSP implicit request object is an instance of a java class that implements
the javax.servlet.http.HttpServletRequest interface. It represents the request
made by the client. The request implicit object is generally used to get request
parameters, request attributes, header information and query string values.

index.html

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
17
welcome.jsp

<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
2.response implicit object
The JSP implicit response object is an instance of a java class that implements the
javax.servlet.http.HttpServletResponse interface. It represents the response to be
given to the client. The response implicit object is generally used to set the response
content type, add cookie and redirect the response.

It can be used to add or manipulate response such as redirect response to another


resource, send error etc.

index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>

3.out implicit object

The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter class. It


represents the output content to be sent to the client. The out implicit object is used to
write the output content.

In case of servlet you need to write: PrintWriter out=response.getWriter();

But in JSP, you don't need to write this code.


Example
index.jsp
<html>
<body>
<% out.print("Hi Welcome to world of Java”); %>
</body>
</html>

4.session implicit object


18
The JSP implicit session object is an instance of a java class that implements the
javax.servlet.http.HttpSession interface. It represents a client specific conversation.
The session implicit object is used to store session state for a single user.
Example of session implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>

second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>

5.application implicit object

The JSP implicit application object is an instance of a java class that implements the
javax.servlet.ServletContext interface. It gives facility for a JSP page to obtain and
set information about the web application in which it is running.

index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
19
</form>
</body>
</html>

welcome.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%

out.println("<h3>Welcome "+request.getParameter("uname")+"</h3>");

String driver=application.getInitParameter("dname");
out.println("<h3>Driver name is="+driver+"</h3>");

%>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd"
version="3.0">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<servlet>
<servlet-name> Anita Lopez</servlet-name>
<jsp-file>welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Anita Lopez</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
20
</web-app>

6.exception implicit object

The JSP implicit exception object is an instance of the java.lang.Throwable class. It


is available in JSP error pages only. It represents the occured exception that caused
the control to pass to the JSP error page.
error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>

7.config implicit object

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

Example of config implicit object:


index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>

<servlet>
<servlet-name>Anita Lopez</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>

<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10. </init-param>
11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name> Anita Lopez </servlet-name>
16. <url-pattern>/welcome</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));

21
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);

5. %>
6. 8.page implicit object

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

9.pageContext implicit object

The JSP implicit pageContext object is an instance of the


javax.servlet.jsp.PageContext abstract class. It provides useful context information.
That is it provides methods to get and set attributes in different scopes and for
transfering requests to other resources. Also it contains the reference to to implicit
objects.

Example of pageContext implicit object


index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

welcome.jsp
<html>
<body>
<%

String name=request.getParameter("uname");
out.print("Welcome "+name);

pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);

<a href="second.jsp">second jsp page</a>

10. %>
11. </body>
12. </html>

second.jsp
<html>
<body>
<%
String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
22
%>
</body>
</html>

Comments and Character Quoting Conventions


There are a small number of special constructs you can use in various cases to insert comments
or characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
<%-- comment -- %> A JSP comment. Ignored by JSP-to-scriptlet
translator. Any embedded JSP
scripting elements, directives, or actions are
ignored.
<!-- comment -- > An HTML comment. Passed through to resultant
HTML. Any embedded
JSP scripting elements, directives, or actions are
executed normally.
<\% Used in template text (static HTML) where you
really want "<%".
%\> Used in scripting elements where you really want
"%>".
\' A single quote in an attribute that uses single
quotes. Remember, however,
that you can use either single or double quotes, and
the other type of quotewill then be a regular
character.
\" A double quote in an attribute that uses double
quotes. Remember,however, that you can use
either single or double quotes, and the other type
of quote will then be a regular character.
%\> %>in an attribute.

<\% <% in an attribute

Expression Language (EL) in JSP


The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean
component, and other objects like request, session, application etc.There are many implicit
objects, operators and reserve words in EL.It is the newly added feature in JSP technology version
2.0.
Syntax for Expression Language (EL)
${ expression }
Implicit Objects in Expression Language (EL)
There are many implicit objects in the Expression Language. They are as follows:
Implicit Objects Usage
pageScope it maps the given attribute name with the value set in
the page scope
requestScope it maps the given attribute name with the value set in
the request scope

23
sessionScope it maps the given attribute name with the value set in
the session scope
applicationScope it maps the given attribute name with the value set in
the application scope
param it maps the request parameter to the single value
paramValues it maps the request parameter to an array of values
header it maps the request header name to the single value
headerValues it maps the request header name to an array of
values
cookie it maps the given cookie name to the cookie value
initParam it maps the initialization parameter
pageContext it provides access to many objects request, session
etc.
Simple example of Expression Language that prints the name of the user
In this example, we have created two files index.jsp and process.jsp. The index.jsp file gets input
from the user and sends the request to the process.jsp which in turn prints the name of the user
using EL.
index.jsp
<form action="process.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.name }
Example of Expression Language that prints the value set in the session scope
In this example, we printing the data stored in the session scope using EL. For this purpose, we
have used sessionScope object.
index.jsp
<h3>welcome to index page</h3>
<%
session.setAttribute("user","sonoo");
%>
<a href="process.jsp">visit</a>
process.jsp
Value is ${ sessionScope.user }

Precedence of Operators in EL
There are many operators that have been provided in the Expression Language. Their precedence
are as follows:
[] .
()

24
-(unary) not ! empty
* / div % mod
+ - (binary)
<<= >>= lt le gtge
== != eq ne
&& and
|| or
?:

Reserve words in EL
There are many reserve words in the Expression Language. They are as follows:
lt le gt ge
eq ne true false
and or not instanceof
div mod empty null

Unified Expression Language


The primary new feature of JSP 2.1 is the unified expression language (unified EL), which
represents a union of the expression language offered by JSP 2.0 and the expression language
created for JavaServer Faces technology

The expression language introduced in JSP 2.0 allows page authors to use simple expressions to
dynamically read data from JavaBeans components.

As explained in The Life Cycle of a JSP Page, JSP supports a simple request/response life cycle,
during which a page is executed and the HTML markup is rendered immediately. Therefore, the
simple, read-only expression language offered by JSP 2.0 was well suited to the needs of JSP
applications.

JavaServer Faces technology, on the other hand, features a multiphase life cycle designed to
support its sophisticated UI component model, which allows for converting and validating
component data, propagating component data to objects, and handling component events. To
facilitate these functions, JavaServer Faces technology introduced its own expression language
that included the following functionality:

 Deferred evaluation of expressions


 The ability to set data as well as get data
 The ability to invoke methods

25
The new, unified expression language allows page authors to use simple expressions to perform
the following tasks:

 Dynamically read application data stored in JavaBeans components, various data structures,
and implicit objects
 Dynamically write data, such as user input into forms, to JavaBeans components
 Invoke arbitrary static and public methods
 Dynamically perform arithmetic operations

The unified EL also allows custom tag developers to specify which of the following kinds of
expressions that a custom tag attribute will accept:

 Immediate evaluation expressions or deferred evaluation expressions. An immediate


evaluation expression is evaluated immediately by the JSP engine. A deferred evaluation
expression can be evaluated later by the underlying technology using the expression language.
 Value expression or method expression. A value expression references data, whereas a
method expression invokes a method.
 Rvalue expression or Lvalue expression. An rvalue expression can only read a value, whereas
an lvalue expression can both read and write that value to an external object.

26

You might also like