You are on page 1of 14

Advanced java programming

Topic: JSP( java server pages)


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 Tags, etc.

Q) Explain jsp engine? Or


Explain jsp Architecture?
JSP architecture gives a high-level view of the working of JSP. JSP architecture is a 3
tier architecture. It has a Client, Web Server, and Database. The client is the web
browser or application on the user side. Web Server uses a JSP Engine i.e; a container
that processes JSP. For example, Apache Tomcat has a built-in JSP Engine. JSP Engine
intercepts the request for JSP and provides the runtime environment for the
understanding and processing of JSP files. It reads, parses, build Java Servlet, Compiles
and Executes Java code, and returns the HTML page to the client. The webserver has
access to the Database. The following diagram shows the architecture of JSP.

Now let us discuss JSP which stands for Java Server Pages. It is a server-side
technology. It is used for creating web applications. It is used to create dynamic web
content. In this JSP tags are used to insert JAVA code into HTML pages. It is an
advanced version of Servlet Technology. It is a Web-based technology that helps us to
create dynamic and platform-independent web pages. In this, Java code can be inserted
in HTML/ XML pages or both. JSP is first converted into a servlet by JSP container
before processing the client’s request. 

Q) How jsp works ?

Step 1: The client navigates to a file ending with the .jsp extension and the


browser initiates an HTTP request to the webserver. For example, the user enters
the login details and submits the button. The browser requests a status.jsp page
from the webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file.
Otherwise, the request is forwarded to the JSP Engine. This is done by recognizing the
URL ending with .jsp extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java code).
This is done by converting all the template text into println() statements and JSP
elements to Java code. This process is called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is forwarded
to the Servlet engine. This process is called compilation or request processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web
Server. The output is an HTML file. The Servlet engine passes the output as an HTTP
response to the webserver.
Step 6: The web server forwards the HTML file to the client’s browser.

Q) Difference between Servlet and JSP ?


The difference between Servlet and JSP is as follows:

Servlet JSP

Servlet is a java code. JSP is a HTML based code.

Writing code for servlet is harder than JSP JSP is easy to code as it is java in
as it is HTML in java. HTML.

Servlet plays a controller role in the MVC JSP is the view in the MVC
approach. approach for showing output.

JSP is slower than Servlet because


the first step in the JSP lifecycle is
the translation of JSP to java code
Servlet is faster than JSP. and then compile.

Servlet can accept all protocol requests. JSP only accepts HTTP requests.

In Servlet, we can override the service() In JSP, we cannot override its


method. service() method.

In Servlet by default session management is


not enabled, user have to enable it In JSP session management is
explicitly. automatically enabled.

In Servlet we have to implement everything In JSP business logic is separated


like business logic and presentation logic in from presentation logic by using
just one servlet file. JavaBeans client-side.

Modification in Servlet is a time-


consumingcompiling task because it
includes reloading, recompiling, JavaBeans JSP modification is fast, just need
and restarting the server. to click the refresh button.
Servlet JSP

In JSP there are inbuilt implicit


It does not have inbuilt implicit objects. objects.

While running the JavaScript at the


There is no method for running JavaScript client side in JSP, the client-side
on the client side in Servlet. validation is used.

Packages can be imported into the


Packages are to be imported on the top of JSP program(i.e bottom , middle
the program. client-side, or top )

Q) The Anatomy of a JSP Page


A JSP page is simply a regular web page with JSP elements for generating the
parts of the page that differ for each request.

Everything in the page that is not a JSP element is called template text . Template
text can really be any text: HTML, WML, XML, or even plain text. Since HTML
is by far the most common web page language in use today, most of the
descriptions and examples in this book are HTML-based, JSP has no dependency
on HTML; it can be used with any markup language. Template text is always
passed straight through to the browser.
Figure: Template text and JSP elements

When a JSP page request is processed, the template text and the dynamic content
generated by the JSP elements are merged, and the result is sent as the response to
the browser.

JSP Elements

There are three types of elements with JavaServer Pages: directive, action,


and scripting elements.

The directive elements, shown in Table are used to specify information about the
page itself that remains the same between page requests, for example, the scripting
language used in the page, whether session tracking is required, and the name of a
page that should be used to report errors, if any.

Table :  Directive Elements


Element Description

<%@ page ...


%> Defines page-dependent attributes, such as scripting language,
error page, and buffering ...

Q) Explain Jsp syntax ?

Or Explain jsp components


Java Server Page (JSP) is a technology for controlling the content or appearance of Web pages through
the use of servlets. Small programs that are specified in the Web page and run on the Web server to
modify the Web page before it is sent to the user who requested it. There are total three Scripting
Element in JSP
1. Scriptlet tag
2. Expression tag
3. Declaration tag
Using these tags we can insert our java code in JSP.

Scriptlet tag

This tag allow user to insert java code in JSP. The statement which is written will be moved to
jspservice() using JSP container while generating servlet from JSP. When client make a request, JSP
service method is invoked and after that the content which is written inside the scriptlet tag executes. 
<html> 
<body> 
<% out.print("Welcome to jsp page"); %> 
</body> 
</html>
Explanation
 The Syntax of JSP Scriptlet tag is begin with ”.
 We can write our java code inside this tag.
 In java we use System.out.println for printing anything on console. In JSP, we use only out.print to
write something on console because the out we’re referring to isn’t System.out, it’s a variable in the
effective method that wraps our JSP page.
 System.out writes to the servlet container’s console (usually a log file); out is a different class
entirely which writes to the output stream for the generated response.

Expression tag is one of the scripting elements in JSP. Expression Tag in JSP is used for writing your
content on the client-side. We can use this tag for displaying information on the client’s browser. The
JSP Expression tag transforms the code into an expression statement that converts into a value in the
form of a string object and inserts into the implicit output object. 
Syntax: JSP tag 

<%= expression %>

 In the Scriptlet tag, it’s Evaluated a Java expression. Does not display any result in the HTML
produced. Variables are declared to have only local scope, so cannot be accessed from elsewhere in
the .jsp. but in Expression Tag it’s Evaluates a Java expression. Inserts the result (as a string) into the
HTML in the .js
 We don’t need to write out.println in Expression tag for printing anything because these are
converted into out.print() statement and insert it into the _jspService(-, -) of the servlet class by the
container.
<html>

<body>

<%= welcome to jsp class%> <!-- Expression tag -->

</body>

</html>

JSP Declaration

 A declaration tag is a piece of Java code for declaring variables, methods and classes. If we
declare a variable or method inside declaration tag it means that the declaration is made inside the
servlet class but outside the service method.
 We can declare a static member, an instance variable (can declare a number or string) and
methods inside the declaration tag.

Syntax of declaration tag:

<%! Dec var %>


Here Dec var is the method or a variable inside the declaration tag.

Q ) Explain java Beans ?


A JavaBean is a specially constructed Java class written in the Java and coded according to the
JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java classes −
 It provides a default, no-argument constructor.
 It should be serializable and that which can implement the Serializable interface.
 It may have a number of properties which can be read or written.
 It may have a number of "getter" and "setter" methods for the properties.

JavaBeans Properties

A JavaBean property is a named attribute that can be accessed by the user of the object. The
attribute can be of any Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class −

S.No. Method & Description


1 getPropertyName()
For example, if property name is firstName, your method name
would be getFirstName() to read that property. This method is
called accessor.

setPropertyName()

2 For example, if property name is firstName, your method name


would be setFirstName() to write that property. This method is
called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only attribute


will have only a setPropertyName() method.

JavaBeans Example

Consider a student class with few properties −

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;
}
}

Accessing JavaBeans

The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used in
the JSP. The full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name
among other useBean declarations in the same JSP.
Following example shows how to use the useBean action −
<html>
<head>
<title>useBean Example</title>
</head>

<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
You will receive the following result − −
The date/time is Thu Sep 30 11:18:11 GST 2010

Accessing JavaBeans Properties

Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the


get methods and the <jsp:setProperty/> action to access the set methods. Here is the full syntax

<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 name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that should be
invoked.
Following example shows how to access the data using the above syntax −
<html>
<head>
<title>get and set properties Example</title>
</head>

<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</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>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed −
Student First Name: Zara

Student Last Name: Ali

Student Age: 10

Jsp session Tracking


Cookies
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the received
cookie.
This may not be an effective way as the browser at times does not support a
cookie. It is not recommended to use this procedure to maintain the sessions.
Hidden Form Fields
A web server can send a hidden HTML form field along with a unique session ID
as follows −
<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value
are automatically included in the GET or the POST data. Each time the web
browser sends the request back, the session_id value can be used to keep the track
of different web browsers.
This can be an effective way of keeping track of the session but clicking on a
regular (<A HREF...>) hypertext link does not result in a form submission, so
hidden form fields also cannot support general session tracking.

The session Object


Apart from the above mentioned options, JSP makes use of the servlet provided
HttpSession Interface. This interface provides a way to identify a user across.
 a one page request or
 visit to a website or
 store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is
instantiated for each new client automatically. Disabling session tracking requires
explicitly turning it off by setting the page directive session attribute to false as
follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the
implicit session object. Since session object is already provided to the JSP
programmer, the programmer can immediately begin storing and retrieving data
from the object without any initialization or getSession().
No. Method & Description

public Object getAttribute(String name)


1 This method returns the object bound with the specified name in this
session, or null if no object is bound under the name.

public Enumeration getAttributeNames()


2 This method returns an Enumeration of String objects containing the
names of all the objects bound to this session.

public long getCreationTime()


3 This method returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.

Q) Sharing Data Between JSP Pages, Requests, and


Users
• Any real application consists of more than a single page
• Multiple pages often need access to the same information and server-side
resources
• e.g., one page that retrieves the data the user asked for and another that displays it
(online shopping application)
Passing Control and Data Between Pages
• Model-View-Controller (MVC) model
– most fundamental features of JSP
– allows for separation of request processing, business logic and presentation
• User Info example
– Display the form for user input (presentation)
– Validate the input (request processing and business logic)
– Display the result of the validation (presentation)

Passing Control and Data


• Using different JSP pages as Controller and View means that more
than one page is used to process a request.
• To make this happen, you need to be able to do two things:
– Pass control from one page to another
– Pass data from one page to another

Passing Control from One Page to Another

• <jsp:forward>action <jsp:forward page=”userinfoinput.jsp”/>


• Action stops processing of one page and starts processing the page specified by
the page attribute (target page)
• Control never returns to the original page
• Target page has access to all information about the request, including all request
parameters
• Can add additional request parameters
<jsp: forward page=”userinfoinput.jsp”>
<jsp:param name=”msg” value=”invalid email address”/>
</jsp:forward>

Passing Data from One Page to Another


• JSP provides different scopes for sharing data objects
• Scope defines how long the object is available and whether it's available only to
one user or to all application users
• Following scopes are defined:
– page, request, session, and application
• page scope (default scope)
– Objects available only within that page
• request scope
– Objects available to all pages processing the same request
• session scope
– Objects available to all requests made from the same browser
• application scope
– Objects shared by all users of the application

  Q) Sharing Session and Application Data


The request scope makes data available to multiple pages processing the same
request. But in many cases, data must be shared over multiple requests.

Imagine a travel agency application. It's important to remember the dates and
destination entered to book the flight so that the customer doesn't have to reenter
the information when it's time to make hotel and rental car reservations. This type
of information, available only to requests from the same user, can be shared
through the session scope.

Some information is needed by multiple pages independent of who the current user
is. JSP supports access to this type of shared information through the application
scope. Information saved in the application scope by one page can later be
accessed by another page, even if the two pages were requested by different users.
Examples of information typically shared through the application scope are
database connection pool objects, information about currently logged-in users, and
cache objects that avoid unnecessary database queries for data that is the same for
all users.

Figure 10-4 shows how the server provides access to the two scopes for different
clients.
Figure 10-4. Session and application scopes

You might also like