You are on page 1of 24

JSP

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.
It focuses more on presentation logic of the web apllication. JSP pages are easier to maintain
then a Servlet. JSP pages are opposite of Servlets. Servlet adds HTML code inside Java code
while JSP adds Java code inside HTML. Everything a Servlet can do, a JSP page can also do it.
JSP enables us to write HTML pages containing tags that run powerful Java programs. JSP
separates presentation and business logic as Web designer can design and update JSP pages
without learning the Java language and Java Developer can also write code without concerning
the web design.
In the end a JSP becomes a Servlet

JSP pages are converted into Servlet by the Web Container. The Container translates a JSP page
into servlet class source(.java) file and then compiles into a Java Servlet class.

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.

Lifecycle of JSP
A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to
a Servlet is called Lifecycle of JSP. JSP Lifecycle consists of following steps.
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method

JSP Processing :
Please find the below steps that are required to process JSP Page
1. Web browser sends an HTTP request to the web server requesting JSP page.
2. Web server recognizes that the HTTP request by web browser is for JSP page
by checking the extension of the file (i.e .jsp)
3. Web server forwards HTTP Request to JSP engine.
4. JSP engine loads the JSP page from disk and converts it into a servlet
5. JSP engine then compiles the servlet into an executable class and forward
original request to a servlet engine.
6. Servlet engine loads and executes the Servlet class.
7. Servlet produces an output in HTML format
8. Output produced by servlet engine is then passes to the web server inside an
HTTP response.
9. Web server sends the HTTP response to Web browser in the form of static
HTML content.
10.Web browser loads the static page into the browser and thus user can view
the dynamically generated page.

JSP Page Anatomy


A JSP page is made up of template data and/or syntactic elements, each of which can be
composed of various components as illustrated by the following diagram:

JSP Scriptlet tag (Scripting elements)

In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the
scripting elements first.JSP 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:

1. <% java source code %>


Example of JSP scriptlet tag

In this example, we are displaying a welcome message.


1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
JSP expression tag

The code placed within JSP 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
1. <%= statement %>
Example of JSP expression tag

In this example of jsp expression tag, we are simply displaying a welcome message.
1. <html>
2. <body>
3. <%= "welcome to jsp" %>
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:


1. <%! field or method declaration %>

Example of JSP declaration tag that declares field

In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
JSP Implicit Objects

There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
A list of the 9 implicit objects is given below:

1) JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the object of
JspWriter. In case of servlet you need to write:
1. PrintWriter out=response.getWriter();

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


Example of out implicit object

In this example we are simply displaying date and time.

index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>

2.JSP request object


The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request
by the web container. It can be used to get request information such as parameter, header
information, remote address, server name, server port, content type, character encoding etc.
It can also be used to set, get and remove attributes from the jsp request scope.
Let's see the simple example of request implicit object where we are printing the name of the
user with welcome message.
Example of JSP request implicit object
index.html
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. String name=request.getParameter("uname");
3. out.print("welcome "+name);
4. %>

3) JSP response implicit object

In JSP, response is an implicit object of type HttpServletResponse. The instance of


HttpServletResponse is created by the web container for each jsp request.
It can be used to add or manipulate response such as redirect response to another resource, send
error etc.
Let's see the example of response implicit object where we are redirecting the response to the
Google.
Example of response implicit object
index.html
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>

welcome.jsp
1. <%
2. response.sendRedirect("http://www.google.com");
3. %>

4) JSP config implicit object(we can write as header 7

th

point)

In JSP, config is an implicit object of type ServletConfig. This object can be used to get
initialization parameter for a particular JSP page. The config object is created by the web
container for each jsp page.
Generally, it is used to get initialization parameter from the web.xml file.
Example of config implicit object:
index.html
1. <form action="welcome">
2. <input type="text" name="uname">

3. <input type="submit" value="go"><br/>


4. </form>
web.xml file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6.
7. <init-param>
8. <param-name>dname</param-name>
9. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10.</init-param>
11.
12.</servlet>
13.
14.<servlet-mapping>
15.<servlet-name>sonoojaiswal</servlet-name>
16.<url-pattern>/welcome</url-pattern>
17.</servlet-mapping>
18.
19.</web-app>
welcome.jsp
1. <%

2. out.print("Welcome "+request.getParameter("uname"));
3.
4. String driver=config.getInitParameter("dname");
5. out.print("driver name is="+driver);
6. %>

5.The session Object:


The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same
way that session objects behave under Java Servlets.
The session object is used to track client session between client requests.

6.The application Object:


The application object is direct wrapper around the ServletContext object for the generated
Servlet and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created
when the JSP page is initialized and will be removed when the JSP page is removed by the
jspDestroy() method.
By adding an attribute to application, you can ensure that all JSP files that make up your web
application have access to it.

7.The config Object:


The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper
around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization
parameters such as the paths or file locations etc.
The following config method is the only one you might ever use, and its usage is trivial:
config.getServletName();

This returns the servlet name, which is the string contained in the <servlet-name> element
defined in the WEB-INF\web.xml file

8.The pageContext Object:


The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The
pageContext object is used to represent the entire JSP page.
This object is intended as a means to access information about the page while avoiding most of
the implementation details.
This object stores references to the request and response objects for each request. The
application, config, session, and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page,
including the buffering information, the errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,
SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also
supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp.
JspContext class.
One of the important methods is removeAttribute, which accepts either one or two arguments.
For example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes,
while the following code only removes it from the page scope:
pageContext.removeAttribute("attrName", PAGE_SCOPE);

9.The page Object:


This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.
The page object is really a direct synonym for the this object.

10.The exception Object:


The exception object is a wrapper containing the exception thrown from the previous page. It is
typically used to generate an appropriate response to the error condition.

JSP - Expression Language (EL)


JSP Expression Language (EL) makes it possible to easily access application data stored in
JavaBeans components. JSP EL allows you to create expressions both (a) arithmetic and (b)
logical. Within a JSP EL expression, you can use integers, floating point numbers, strings, the
built-in constants true and false for boolean values, and null.

Simple Syntax:
Typically, when you specify an attribute value in a JSP tag, you simply use a string. For example:
<jsp:setProperty name="box" property="perimeter" value="100"/>

JSP EL allows you to specify an expression for any of these attribute values. A simple syntax for
JSP EL is as follows:
${expr}

Here expr specifies the expression itself. The most common operators in JSP EL are . and [].
These two operators allow you to access various attributes of Java Beans and built-in JSP
objects.
For example above syntax <jsp:setProperty> tag can be written with an expression like:
<jsp:setProperty name="box" property="perimeter"
value="${2*box.width+2*box.height}"/>

When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate the
expression and substitues the value of expresson.
You can also use JSP EL expressions within template text for a tag. For example, the <jsp:text>
tag simply inserts its content within the body of a JSP. 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) with the
same ${} syntax you use for attributes. For example:
<jsp:text>
Box Perimeter is: ${2*box.width + 2*box.height}
</jsp:text>

EL expressions can use parentheses to group subexpressions. For example, ${(1 + 2) * 3} equals
9, but ${1 + (2 * 3)} equals 7.
To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page
directive as below:
<%@ page isELIgnored ="true|false" %>

The valid values of this attribute are true and false. If it is true, EL expressions are ignored when
they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the
container.

MVC in JSP

MVC stands for Model View and Controller. It is a design pattern that separates the business
logic, presentation logic and data.
Controller acts as an interface between View and Model. Controller intercepts all the incoming
requests.
Model represents the state of the application i.e. data. It can also have business logic.
View represents the presentaion i.e. UI(User Interface).
Advantage of MVC (Model 2) Architecture
1. Navigation Control is centralized
2. Easy to maintain the large application

JSP - Exception Handling


When you are writing JSP code, a programmer may leave a coding errors which can occur at any
part of the code. You can have following type of errors in your JSP code:

Checked exceptions: Achecked exception is an exception that is typically a user error or


a problem that cannot be foreseen by the programmer. For example, if a file is to be
opened, but the file cannot be found, an exception occurs. These exceptions cannot
simply be ignored at the time of compilation.

Runtime exceptions: A runtime exception is an exception that occurs that probably could
have been avoided by the programmer. As opposed to checked exceptions, runtime
exceptions are ignored at the time of compliation.

Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely
do anything about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.

Using Exception Object:


The exception object is an instance of a subclass of Throwable (e.g., java.lang.
NullPointerException) and is only available in error pages.
JSP gives you an option to specify Error Page for each JSP. Whenever the page throws an
exception, the JSP container automatically invokes the error page.
Following is an example to specifiy an error page for a main.jsp. To set up an error page, use the
<%@ page errorPage="xxx" %> directive.

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


<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
// Throw an exception to invoke the error page
int x = 1;
if (x == 1)
{
throw new RuntimeException("Error condition!!!");
}

%>
</body>
</html>

Now you would have to write one Error Handling JSP ShowError.jsp, which is given
below. Notice that the error-handling page includes the directive <%@ page
isErrorPage="true" %>. This directive causes the JSP compiler to generate the exception
instance variable.

<%@ page isErrorPage="true" %>


<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>

Now try to access main.jsp, it should generate something as follows:

java.lang.RuntimeException: Error condition!!!


......
Opps...
Sorry, an error occurred.

Using Try...Catch Block:


If you want to handle errors with in the same page and want to take some action instead of firing
an error page, you can make use of try....catch block.
Following is a simple example which shows how to use try...catch block. Let us put following
code in main.jsp:
<html>
<head>
<title>Try...Catch Example</title>
</head>
<body>
<%
try{
int i = 1;

i = i / 0;
out.println("The answer is " + i);
}
catch (Exception e){
out.println("An exception occurred: " + e.getMessage());
}
%>
</body>
</html>

Now try to access main.jsp, it should generate something as follows:

An exception occurred: / by zero

Installing Tomcat, Java and testing Tomcat Server


Here we define steps to do this:
1. Download Apache Tomcat server on your computer.
2. Navigate on: http://tomcat.apache.org/download
3. Installation of JDK:
Before beginning the process of installing Tomcat on your system, ensure first the
availability of JDK on your system program directory. Install it on your system if not
already installed (because any version of tomcat requires the Java 1.6 or higher versions)
and then set the class path (environment variable) of JDK. To set the JAVA_HOME
Variable: you need to specify the location of the java run time environment to support the
Tomcat else Tomcat server can not run.
This variable contains the path of JDK installation directory.
Start menu->Control Panel->System->Advanced tab>Environment Variables->New->set the Variable name =
JAVA_HOME and variable value = C:\Program
Files\Java\jdk1.6
Now click on all the subsequent ok buttons one by one. It will set the JDK path.
4.For setting the class path variable for JDK, do like this:
Start menu->Control Panel->System->Advanced tab>Environment Variables->New->
Set PATH="C:\Program Files\Java\jdk1.6\bin"; %PATH
%

OR
First, right click on the
My Computer->properties->advance->Environment
Variables->path.
Now, set bin directory path of JDK in the path variable
5. The process of installing Tomcat 6.0 begins here from now. It takes various steps for installing
and configuring the Tomcat 6.0.
For Windows OS, Tomcat comes in two forms: .zip file and .exe file (the Windows installer file).
Here we are exploring the installation process by using the .exe file. First unpack the zipped file
and simply execute the '.exe' file.
6.After completing the installation process, the Apache Tomcat Manager appears on
the toolbar panel like shown in the below picture.

7.Testing tomcat: Start the Tomcat Server:


1).Start the tomcat server from the bin folder of Tomcat 6.0 directory by double clicking the
"tomcat6.exe" file.
OR create a shortcut of this .exe file at your desktop.
2). Now Open web browser and type URL http://localhost:8080 in the address bar to test the
server
3.) To Stop the Tomcat Server: Stop the server by pressing the "Ctrl + c" keys.

Using Beans in jsp: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


<jsp:useBean id= "instanceName" scope= "page | request | session | applicat
ion"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</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.

request: specifies that you can use this bean from any JSP page that
processes the same request. It has wider scope than page.

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.

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()
method.
Simple example of jsp:useBean action tag

In this example, we are simply invoking the method of the Bean class.
Calculator.java (a simple Bean class)

1. package com.javatpoint;

2. public class Calculator{


3.
4. public int cube(int n){return n*n*n;}
5.
6. }
index.jsp file
1. <jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
2.
3. <%
4. int m=obj.cube(5);
5. out.print("cube of 5 is "+m);
6. %>

Struts Framework

This page will give you a short overview of Struts Framework and its main components. After
finishing reading this, continue on to the tutorial to create a simple Struts-based Web application.

What Is the Struts Framework?


The Struts Framework is a standard for developing well-architected Web applications. It has the
following features:

Open source

Based on the Model-View-Controller (MVC) design paradigm, distinctly


separating all three levels:
o

Model: application state

View: presentation of data (JSP, HTML)

Controller: routing of the application flow

Implements the JSP Model 2 Architecture

Stores application routing information and request mapping in a single core


file, struts-config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model
layer is left to the developer.

All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration
file struts-config.xml is used by the controller to determine the routing of the flow. This
flows consists of an alternation between two transitions:
From View to A user clicks on a link or submits a form on an HTML or JSP page. The controller
Action
receives the request, looks up the mapping for this request, and forwards it to an
action. The action in turn calls a Model layer (Business layer) service or function.

After the call to an underlying function or service returns to the action class, the
From Action
action forwards to a resource in the View layer and a page is displayed in a web
to View
browser.

Struts Components
The Controller

This receives all incoming requests. Its primary function is the mapping of a request URI to an
action class selecting the proper application module. It's provided by the framework.
The struts-config.xml File

This file contains all of the routing and configuration information for the Struts application. This
XML file needs to be in the WEB-INF directory of the application.
Action Classes

It's the developer's responsibility to create these classes. They act as bridges between userinvoked URIs and business services. Actions process a request and return an ActionForward
object that identifies the next component to invoke. They're part of the Controller layer, not the
Model layer.
View Resources

View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files,
Resource bundles, JavaBeans, and Struts JSP tags.
ActionForms

These greatly simplify user form validation by capturing user data from the HTTP request. They
act as a "firewall" between forms (Web pages) and the application (actions). These components
allow the validation of user input before proceeding to an Action. If the input is invalid, a page
with an error can be displayed.
Model Components

The Struts Framework has no built-in support for the Model layer. Struts supports any model
components:

JavaBeans

EJB

CORBA

JDO

any other

You might also like