0% found this document useful (0 votes)
5 views25 pages

Unit 2

The document provides study material on Advanced Java Programming, specifically focusing on Java Server Pages (JSP) and the Model-View-Controller (MVC) architecture. It outlines the JSP life cycle, including compilation, initialization, execution, and cleanup, and explains the MVC pattern's components: Model, View, and Controller. Additionally, it includes examples of JSP scripting elements, directives, and a simple MVC-based JSP application for user login functionality.

Uploaded by

rjfdfn8rjd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views25 pages

Unit 2

The document provides study material on Advanced Java Programming, specifically focusing on Java Server Pages (JSP) and the Model-View-Controller (MVC) architecture. It outlines the JSP life cycle, including compilation, initialization, execution, and cleanup, and explains the MVC pattern's components: Model, View, and Controller. Additionally, it includes examples of JSP scripting elements, directives, and a simple MVC-based JSP application for user login functionality.

Uploaded by

rjfdfn8rjd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

THE NEW COLLEGE (AUTONOMOUS), CHENNAI-14.

Department of Computer Applications – Shift - II


Study Material
Subject: Advanced Java Programming (20BHM407) Class: II BCA
---------------------------------------------------------------------------------------------------------------------------------
UNIT-II
1. INTRODUCTION TO JSP
JSP stands for Java Server Pages is a technology for building web applications that support dynamic content and acts
as a Java servlet technology. This 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 fulfil 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 Webpage forms, present records from a database or another
source, and create Webpages 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.
1.1. Life Cycle of JSP
A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle
with an additional step which is required to compile a JSP into servlet.

The following are the paths followed by a JSP


 Compilation
 Initialization
 Execution
 Clean up
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four phases have been
described below

1. 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.(Analysing)
 Turning the JSP into a servlet. (Converting)
 Compiling the servlet. (Collecting)

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 1 of 25
2. 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... }

Typically, initialization is performed only once and as with the servlet init method, you generally initialize database
connections, open files, and create lookup tables in the jspInit method.

3. 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... }

The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the response for
that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET,
POST, DELETE, etc.

4. 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.
The jspDestroy() method has the following form –

public void jspDestroy()


{ // your cleanup code goes here. }

2. EXAMINING MVC AND JSP (Java Server Pages)


MVC stands for Model View Controller. MVC is an architectural Pattern that separates business logic, presentation
and data. MVC is a systematic way to use the application where the flow starts from the view layer, where the request
is raised and processed in controller layer and sent to model layer to insert data and get back the success or failure
message. The MVC Architecture diagram is represented below:

Fig. MVC Architecture

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 2 of 25
i. Model Layer
 This is the data layer which consists of the business logic of the system.
 It consists of all the data of the application
 It also represents the state of the application.
 It consists of classes which have the connection to the database.
 The controller connects with model and fetches the data and sends to the view layer.
 The model connects with the database as well and stores the data into a database which is connected to it.
ii. View Layer
 This is a presentation layer.
 It consists of HTML, JSP, etc. into it.
 It normally presents the UI of the application.
 It is used to display the data which is fetched from the controller which in turn fetching data from model layer
classes.
 This view layer shows the data on UI of the application.
iii. Controller Layer
 It acts as an interface between View and Model.
 It intercepts all the requests which are coming from the view layer.
 It receives the requests from the view layer and processes the requests and does the necessary validation for
the request.
 This request is further sent to model layer for data processing, and once the request is processed, it sends back
to the controller with required information and displayed accordingly by the view.
Advantages of MVC Architecture
 Easy to maintain
 Easy to extend
 Easy to test
 Navigation control is centralized

2.1 Usage of MVC and JSP Application


Here’s a simple example of an MVC-based JSP application that demonstrates a user login system:
Folder Structure
- WebContent/
- index.jsp
- login.jsp
- success.jsp
- src/
- com.example.model.User.java
- com.example.service.LoginService.java
- com.example.controller.LoginController.java

1. Model (User.java)
This class represents the user data.
package com.example.model;
public class User
{
private String username;
private String password;
public User(String username, String password) { this.username = username; this.password = password; }
public String getUsername() { return username; }
public String getPassword() { return password; }
}

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 3 of 25
2. Service (LoginService.java)
This service handles business logic (e.g., user authentication).
package com.example.service;
import com.example.model.User;
public class LoginService
{
public boolean authenticate(User user)
{ return "admin".equals(user.getUsername()) && "password".equals(user.getPassword()); }
}

3. Controller (LoginController.java)
This servlet processes user requests and forwards responses to the appropriate JSP page.
package com.example.controller;
import com.example.model.User;
import com.example.service.LoginService;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginController extends HttpServlet
{
private final LoginService loginService = new LoginService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");

User user = new User(username, password);

if (loginService.authenticate(user))
{
request.setAttribute("username", username);
RequestDispatcher dispatcher = request.getRequestDispatcher ("success.jsp");
dispatcher.forward(request, response);
}
else
{
response.sendRedirect("login.jsp");
}
}
}

4. View (JSP Pages)


index.jsp
The entry point of the application.
<!DOCTYPE html>
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 4 of 25
<html>
<head>
<title>Login App</title>
</head>
<body>
<h1>Welcome to the Login Application</h1>
<a href="login.jsp">Login</a>
</body>
</html>
login.jsp
The login form.
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="login" method="post">
<label>Username:</label>
<input type="text" name="username" required><br>
<label>Password:</label>
<input type="password" name="password" required><br>
<button type="submit">Login</button>
</form>
</body>
</html>
success.jsp
The success page displayed after successful login.
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Login Successful!</h1>
<p>Welcome, ${username}!</p>
</body>
</html>

5. Deployment and Output


 Deploy the application on a servlet container like Apache Tomcat.
 Access the application via http://localhost:8080/YourApp/index.jsp.
 Click on the login link, enter admin as the username and password as the password.
 On successful login, the success.jsp page displays a welcome message.

This demonstrates a basic MVC design pattern using JSP and Servlets. You can extend this further by integrating
database connectivity for dynamic user management.

3. JSP SCRIPTING ELEMENTS – (Java Server Pages)


We will be learning the basic tags of JSP and how to add comments into JSP. Along with this, we will also create a
JSP and run that JSP on the server.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 5 of 25
i. JSP Declaration
ii. JSP Scriptlet
iii. JSP Expression
iv. JSP Comments

i. 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:
<%! Dec var %> - Here Dec var is the method or a variable inside the declaration tag.

Example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Declaration Tag</title>
</head>
<body>
<%! int count =10; %>
<% out.println ("The Number is” +count); %>
</body>
</html>
Output:

ii. JSP Scriptlet


 Scriptlet tag allows to write Java code into JSP file.
 JSP container moves statements in _jspservice() method while generating servlet from jsp.
 For each request of the client, service method of the JSP gets invoked hence the code inside the Scriptlet executes
for every request.
 A Scriptlet contains java code that is executed every time JSP is invoked.

Syntax:
<% java code %> - Here < %%> tags are scriplets tag and within it, we can place java code.

Example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Scriplet</title>
</head>
<body>
<% int num1=10;
int num2=40;
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 6 of 25
int num3 = num1+num2;
out.println ("Scriplet Number is” +num3); %>
</body>
</html>

Output

iii. JSP Expression


 Expression tag evaluates the expression placed in it.
 It accesses the data stored in stored application.
 It allows create expressions like arithmetic and logical.
 It produces scriptless JSP page.
Syntax:
<%= expression %> - Here the expression is the arithmetic or logical expression.

Example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Expression</title>
</head>
<body>
<% out.println("The expression number is "); %>
<% int num1=10; int num2=10; int num3 = 20; %>
<%= num1*num2+num3 %>
</body>
</html>

Output:

iv. JSP Comments


Comments are the one when JSP container wants to ignore certain texts and statements. When we want to hide certain
content, then we can add that to the comments section.

Syntax:
<% -- JSP Comments-- %> this tags are used to comment in JSP and ignored by the JSP container.
<!—comment –> this is HTML comment which is ignored by browser

Example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Comments</title>
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 7 of 25
</head>
<body>
<%-- Guru Comments section --%>
<% out.println("This is comments example"); %>
</body>
</html>

Output:

4. JSP DIRECTIVES
 JSP directives are the messages to JSP container. They provide global information about an entire JSP page.
 It is used to give special instruction to a container for translation of JSP to servlet code.
 In JSP life cycle phase, JSP has to be converted to a servlet which is the translation phase.
 They give instructions to the container on how to handle certain aspects of JSP processing
 Directives can have many attributes by comma separated as key-value pairs.
 In JSP, directive is described in <%@ %> tags.

Syntax
<%@ directive attribute="" %>

Types of JSP directives:


1. Page directive
2. Include directive
3. Taglib directive

4.1 JSP PAGE DIRECTIVE


 It provides attributes that get applied to entire JSP page.
 It defines page dependent attributes, such as scripting language, error page, and buffering requirements.
 It is used to provide instructions to a container that pertains to current JSP page.

Syntax
<%@ page… %>

Following are its list of attributes associated with page directive:


1. Language
2. Extends
3. Import
4. contentType
5. info
6. session
7. isThreadSafe
8. autoflush
9. buffer
10. IsErrorPage
11. pageEncoding
12. errorPage
13. isELIgonored
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 8 of 25
1. Language: It defines the programming language (underlying language) being used in the page.
Syntax of language:
<%@ page language="value" %> Here value is the programming language (underlying language)
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

Explanation of code: In the above example, attribute language value is Java which is the underlying language in this
case. Hence, the code in expression tags would be compiled using java compiler.

2. Extends: This attribute is used to extend (inherit) the class like JAVA does
Syntax of extends:
<%@ page extends="value" %> Here the value represents class from which it has to be inherited.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@
page extends="demotest.DemoClass" %>

Explanation of the code: In the above code JSP is extending DemoClass which is within demotest package, and it
will extend all class features.

3. Import: This attribute is most used attribute in page directive attributes. It is used to tell the container to import
other java classes, interfaces, enums, etc. while generating servlet code. It is similar to import statements in java
classes, interfaces.
Syntax of import:
<%@ page import="value" %> Here value indicates the classes which have to be imported.

Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"import="java.util.Date"
pageEncoding="ISO-8859-1"%>

Explanation of the code:


In the above code, we are importing Date class from java.util package (all utility classes), and it can use all methods of
the following class.

4. contentType:
 It defines the character encoding scheme i.e. it is used to set the content type and the character set of the
response
 The default type of contentType is “text/html; charset=ISO-8859-1”.

Syntax of the contentType:


<%@ page contentType="value" %>

Example:
<%@ page language="java" contentType="text/html”; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

Explanation of the code: In the above code, the content type is set as text/html, it sets character encoding for JSP and
for generated response page.
5. info
 It defines a string which can be accessed by getServletInfo() method.
 This attribute is used to set the servlet description.

Syntax:
<%@ page info="value" %> Here, the value represents the servlet information.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 9 of 25
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" info="Guru Directive JSP"
pageEncoding="ISO-8859-1"%>

Explanation of the code:


In the above code, string “Guru Directive JSP” can be retrieved by the servlet interface using getServletInfo()

6. Session
 JSP page creates session by default.
 Sometimes we don’t need a session to be created in JSP, and hence, we can set this attribute to false in that
case. The default value of the session attribute is true, and the session is created.
When it is set to false, then we can indicate the compiler to not create the session by default.
Syntax:
<%@ page session="true/false"%> ---- Here in this case session attribute can be set to true or false

Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" session="false"%>

Explanation of code:
In the above example, session attribute is set to “false” hence we are indicating that we don’t want to create any
session in this JSP

7. isThreadSafe:
 It defines the threading model for the generated servlet.
 It indicates the level of thread safety implemented in the page.
 Its default value is true so simultaneous
 We can use this attribute to implement SingleThreadModel interface in generated servlet.
Syntax:
<% @ page isThreadSafe="true/false" %>
Here true or false represents if synchronization is there then set as true and set it as false.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" isThreadSafe="true"%>
Explanation of the code:
In the above code, isThreadSafe is set to “true” hence synchronization will be done, and multiple threads can be used.

8. AutoFlush:
This attribute specifies that the buffered output should be flushed automatically or not and default value of that
attribute is true.
If the value is set to false the buffer will not be flushed automatically and if it’s full, we will get an exception.
When the buffer is none then the false is illegitimate, and there is no buffering, so it will be flushed automatically.
Syntax:
<% @ page autoFlush="true/false" %>
Here true/false represents whether buffering has to be done or not
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" autoFlush="false"%>
Explanation of the code:
In the above code, the autoflush is set to false and hence buffering won’t be done and it has manually flush the output.

9. Buffer:
 Using this attribute the output response object may be buffered.
 We can define the size of buffering to be done using this attribute and default size is 8KB.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 10 of 25
 It directs the servlet to write the buffer before writing to the response object.
Syntax:
<%@ page buffer="value" %>
Here the value represents the size of the buffer which has to be defined. If there is no buffer, then we can write as
none, and if we don’t mention any value then the default is 8KB
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" buffer="16KB"%>

Explanation of the code:


In the above code, buffer size is mentioned as 16KB wherein the buffer would be of that size.

10. isErrorPage:
 It indicates that JSP Page that has an errorPage will be checked in another JSP page
 Any JSP file declared with “isErrorPage” attribute is then capable to receive exceptions from other JSP pages
which have error pages.
 Exceptions are available to these pages only.
 The default value is false.
Syntax:
<%@ page isErrorPage="true/false"%>
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" isErrorPage="true"%>
Explanation of the code:
In the above code, isErrorPage is set as true. Hence, it will check any other JSPs has errorPage (described in the next
attribute) attribute set and it can handle exceptions.

11. PageEncoding:
The “pageEncoding” attribute defines the character encoding for JSP page.
The default is specified as “ISO-8859-1” if any other is not specified.
Syntax:
<%@ page pageEncoding="vaue" %>
Here value specifies the charset value for JSP
Example:
<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1" isErrorPage="true"%>

Explanation of the code:


In the above code “pageEncoding” has been set to default charset ISO-8859-1

12. errorPage:
This attribute is used to set the error page for the JSP page if JSP throws an exception and then it redirects to the
exception page.
Syntax :
<%@ page errorPage="value" %>
Example:
<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"errorPage="errorHandler.jsp"%>

Explanation of the code:


In the above code, to handle exceptions we have errroHandler.jsp.

13. isELIgnored:
 IsELIgnored is a flag attribute where we have to decide whether to ignore EL tags or not.
 Its datatype is java enum, and the default value is false hence EL is enabled by default.
Syntax:
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 11 of 25
<%@ page isELIgnored="true/false" %>
Here, true/false represents the value of EL whether it should be ignored or not.
Example:
<%@ page language="java" contentType="text/html;" pageEncoding="ISO-8859-1"isELIgnored="true"%>
Explanation of the code:
In the above code, isELIgnored is true and hence Expression Language (EL) is ignored here.

4.2 JSP INCLUDE DIRECTIVE


 JSP “include directive”( codeline 8 ) is used to include one file to the another file
 This included file can be HTML, JSP, text files, etc.
 It is also useful in creating templates with the user views and break the pages into header & footer and sidebar
actions.
 It includes file during translation phase
Syntax:
<%@ include…. %>
Example:
Directive_jsp2.jsp (Main file)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<%@ include file="directive_header_jsp3.jsp" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Directive JSP2</title>
</head>
<body>
<a>This is the main file</a>
</body>
</html>

Directive_header_jsp3.jsp (which is included in the main file)


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<a>Header file : </a>
<% int count =1; count++;
out.println(count);%> :
</body>
</html>

Explanation of the code:


Directive_jsp2.jsp:
Code Line 3: In this code, we use include tags where we are including the file directive_header_jsp3.jsp into the main
file(_jsp2.jsp)and gets the output of both main file and included file.

Directive_header_jsp3.jsp:
Code Line 11-12: We have taken a variable count initialized to 1 and then incremented it. This will give the output in
the main file as shown below.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 12 of 25
Output:
 The output is Header file: 2 : This is the main file
 The output is executed from the directive_jsp2.jsp file while the directive_header_jsp3.jsp included file will
be compiled first.
 After the included file is done, the main file is executed, and the output will be from the main file “This is the
main file”. So you will get the output as “Header file: 2” from _jsp3.jsp and “This is main file” from _jsp2.jsp.

4.3 JSP TAGLIB DIRECTIVE


 JSP taglib directive is used to define the tag library with “taglib” as the prefix, which we can use in JSP.
 More detail will be covered in JSP Custom Tags section
 JSP taglib directive is used in the JSP pages using the JSP standard tag libraries
 It uses a set of custom tags, identifies the location of the library and provides means of identifying custom tags
in JSP page.
Syntax of taglib directive:
<%@ taglib uri="uri" prefix="value"%>
Here “uri” attribute is a unique identifier in tag library descriptor and “prefix” attribute is a tag name.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="gurutag" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Directive JSP</title>
<gurutag:hello/>
</head>
<body>
</body>
</html>

5. Working with Variables in JSP Scopes (Range/Capacity)


JSP Scopes
In Java applications, to define data availability i.e. scope for we have to use access specifies public, protected,
default, and private. Similarly, to form available data to a number of resources JSP technologies has provided the
scopes with the access modifiers.
Objects, whether explicit or implicit in a JSP page, are accessible within a particular scope.
For an explicit object, such as a JavaBean instance created in a jsp:useBean action, we can explicitly set the scope
with the following
Syntax:
scope=”scopevalue”

There are four possible scopes:


1. Page Scope
2. Request Scope
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 13 of 25
3. Session Scope
4. Application Scope

1. Page Scope in JSP


Page scope is managed by the page Context object. As a page context object is created for every JSP page, so, every
JSP page will have a specific page scope.
Page Scope is the default scope. The object is accessible only from within the JSP page where it had been created.
A page-scope object is stored within the implicit page Context object. The page scope ends when the page stops
executing.
Example:
pagescope.jsp
<html>
<head>
<title>JSP Page Scope Example</title>
</head>
<body>
<c:set var="name" value="Manisha" scope="page" />
Local Variable : <c:out value="${name}" />
<a href="pagescope2.jsp">Test Page</a>
</body>
</html>
pagescope2.jsp
<html>
<head>
<title>JSP Page Scope Example</title>
</head>
<body>
Variable From previous page : <c:out value="${name}" />
</body>
</html>
Output
Run your code to get the following output:

After clicking on the “Test Page” link, you will get the following output:

2. Request Scope in JSP


Request scope is managed by the request object. This object is used for reading the request object. If the same request
is shared by more than one JSP page those sharing the same request object come under the same request scope.

Request Scope begins whenever the request object is created by the servlet container and the request scope ends
whenever the request object is deleted by the servlet container.

As the request object is stored in the page Context object we can manage request scope attributes by using the page
Context object.

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 14 of 25
Example
In this example, we have created two JSPs: “requestscope.jsp” and “requestscope2.jsp”. On requestscope.jsp we have
created a local variable name that has a value “Manisha” and assigned a “request” scope to it. We have also used
jsp:forward tag to forward the same request to another JSP, i.e. requestscope2.jsp.

Whenever we will run requestscope.jsp it does not print anything and forwards the request to requestscope2.jsp.
Because the variable has a request scope which is accessible in the current request and on any page as long as the
request remains the same.

requestscope.jsp
<html>
<head>
<title>JSP Request Scope Example</title>
</head>
<body>
<c:set var="name" value="Manisha" scope="request" />
<jsp:forward page="requestscope2.jsp"></jsp:forward>
</body>
</html>

requestscope2.jsp
<html>
<head>
<title>JSP Request Scope Example</title>
</head>
<body>
Variable From previous page:
<c:out value="${name}" />
</body>
</html>

Output
Run your code to get the following output:

3. Session Scope in JSP


Session scope is managed by the session object. The same session object is available to all JSP pages as long as the
session is not expired.

Whenever a session is expired or session.invalidate() is called then a new session is created for the next requesting
page. This object is used for reading attributes from HTTPSession.

The object is accessible from any JSP page that’s sharing an equivalent HTTP session because of the JSP page that
created the thing.

A session-scope object is stored within the implicit session object. The session scope ends when the HTTP session
times out or is invalidated.

If we declare the info in HTTPSession object then that data should have the scope up to the number of resources that
are visited by this client.
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 15 of 25
Example
In this example we have created two JSPs: sessionscope.jsp and sessionscope2.jsp. On sessionscope.jsp we have
created local variable “name” which has a value “Manisha” and have assigned “session” scope to it. We also provided
a link on sessionscope.jsp that point to another JSP, i.e. sessionscope2.jsp.

So, when you will run the sessionscope.jsp page it will print the variable name. And when you will click on the link it
goes to the second page and also printed the variable value defined in the first JSP. Because it has a session scope that
is accessible in only that session so during the current session that variable can be accessed from any JSPs.

sessionscope.jsp
<html>
<head>
<title>JSP Session Scope Example</title>
</head>
<body>
<c:set var="name" value="Manisha" scope="session" />
Local Variable :
<c:out value="${name}" />
<a href="sessionscope2.jsp">Test Page</a>
</body>
</html>

sessionscope2.jsp
<html>
<head>
<title>JSP Session Scope Example</title>
</head>
<body>
Variable From previous page :
<c:out value="${name}" />
</body>
</html>

Output
Run your code to get the following output:

After clicking on the “Test Page” link, you will get the following output:

4. Application Scope in JSP


The application scope is maintained by the application pointing object. Application scope begins whenever the
ServletContext implementation object is created.

Application scope ends whenever the ServletContext implementation object is deleted. This object is used for reading
attributes from Servlet Context. The object is accessible from any JSP page that’s utilized in an equivalent
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 16 of 25
Web application because the JSP page that created the thing, within any single Java virtual machine. The concept is
analogous thereto of a Java static variable.

An application-scope object is stored within the implicit application servlet context object. The application scope ends
when the appliance itself terminates, or when the JSP container or servlet container shuts down.

If we declare the info in the Servlet Context object then that data should have the scope up to the number of resources
that are available within the present web application.

Example
In this example, we have created two JSps: applicationscope.jsp and applicationscope2.jsp. On applicationscope.jsp
we have created a local variable “name which has a value “Manisha” and assigned “application” scope to it. We have
also provided a link on applicationscope.jsp that point to another JSP, i.e. applicationscope2.jsp. Whenever you will
any of the JSP pages or you will click on the provided link it will print the variable value.

applicationscope.jsp
<html>
<head>
<title>JSP Application Scope Example</title>
</head>
<body>
<c:set var="name" value="Manisha" scope="application" />
Local Variable : <c:out value="${name}" />
<a href="applicationscope2.jsp">Test Page</a>
</body>
</html>

applicationscope2.jsp
<html>
<head>
<title>JSP Application Scope Example</title>
</head>
<body>
Variable From previous page :<c:out value="${name}" />
</body>
</html>
Output:

After clicking on the “Test Page”, you will get the following output:

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 17 of 25
6. JSP EXCEPTION (ERROR PAGES)
Exceptions occur when there is an error in the code either by the developer or internal error from the system.
Exception handling in JSP is same as in java where we manage exceptions using try catch blocks.
Unlike Java, there are exceptions in JSP also when there is an error in the code.
Types of Exceptions:
1. Checked Exception
2. Runtime Exception
3. Errors Exception
1. Checked Exceptions
It is normally a user error or problems which are not seen by the developer are termed as checked exceptions.

Examples:
FileNotFound Exception: where it tries to find a file when the file is not found on the disk.
IO Exception: if there is any exception occurred during reading or writing of a file then the IO exception is raised.
SQL Exception: when the file is connected with SQL database, and there is issue with the connectivity of the SQL
database.

2. Runtime Exceptions
Runtime exceptions are the one which could have avoided by the programmer. They are ignored at the time of
compilation.
Examples:
• ArrayIndexOutOfBounds Exception: when array size exceeds the elements.
• Arithmetic Exception: when there are any mathematical operations, which are not permitted under normal
conditions,
Example, dividing a number by 0 will give an exception.
• NullPointer Exception: which is raised when a variable or an object is null when we try to access the same.
This is a very common exception.

3. Error Exception
It is an instance of the throwable class, and it is used in error pages.
Examples: Some methods of throwable class are:
Public String getMessage() – returns the message of the exception.
Public throwablegetCause() – returns cause of the exception
Public printStackTrace()- returns the stacktrace of the exception.

Example program (Program for Error Pages in JSP)


index.jsp
<html>
<body>
<form action="process.jsp">
Enter the first Number :< input type="text" name="n1">
Enter the second Number :< input type="text" name="n2">
<input type="submit" value="Calculate">
</form>
</body>
</html>

process.jsp
<html>
<body>
<%@page errorPage="error.jsp"%>
<% String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 18 of 25
int b=Integer.parseInt(num2);
int c=a/b;
out.println("Division of number is:"+c); %>
</body>
</html>

error.jsp
<html>
<body>
<%@page isErrorPage="true"%>
Sorry, an Exception has occured! Exception is <%=exception %>
<form action="index.jsp">
<input type="submit" value="Re-Compute">
</form>
</body>
</html>

Output

7. JAVA BEANS IN JSP


A Java Bean 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 Java Bean 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.

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 19 of 25
Java Beans 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

getPropertyName()
1 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 (Java Beans - ReUsable Components)


Consider a student class with few properties
package com.tutorialspoint;
import java.io.Serializable;
public class StudentsBean implements java.io.Serializable //Class
{
private String firstName = null; //Member Variables with Private Access Specifier
private String lastName = null;
private int age = 0;

public StudentsBean() { } //Default Constructor

public String getFirstName(){ return firstName; } //Getter Method with Public Access Specifier
public String getLastName(){ return lastName; }
public int getAge(){ return age; }

public void setFirstName(String firstName){this.firstName=firstName}//Setter method with Public Access Specifier


public void setLastName(String lastName){ this.lastName = lastName;}
public void setAge(Integer age){ this.age = age; }
}

8. WORKING WITH JAVA MAIL


Sending an E-Mail Using JSP in Java
1. Open the NetBeans IDE.
2. Choose "Java web" -> "Web application" as in the following.
3. Specify "JSPMailApp" as the project name as in the following.
4. Select the Server and version wizard as in the following.
5. Now delete the default "index. ...
6. Now create a new JSP page "mailJSP.
This chapter explains how to send an email using JSP in Java. The NetBeans IDE is used to create this app.

Sending an Email in JSP


In other words, the JavaMail API. This API is created in various ways, but in this article I'll show you a simple format
by which you can easily develop your own mail API. Our Mail API is based on the two protocols SMTP and MIME.

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 20 of 25
Let's start creating this app
We need to follow several steps in the NetBeans IDE.
Step 1 : Open the NetBeans IDE.

Step 2 : Choose "Java web" -> "Web application" as in the following.

Step 3 : Specify "JSPMailApp" as the project name as in the following.

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 21 of 25
Step 4 : Select the Server and version wizard as in the following.

Step 5
Now delete the default "index.jsp" file and create a new "index.html" file with the following code.
This page is created to receive the values from the user, like mail-id, subject and message content that they want to
send. Then we send these details to the "mailJSP.jsp" page to respond depending on them.

index.html
<!DOCTYPE html>
<html>
<head>
<title>Sending Mail Through JSP</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body bgcolor="khaki">
<form action="mailJSP.jsp">
<table>
<tr><td><b><font color="red">To:
</td>
<td><b><b><input type="text" name="mail" value="Enter sender mail-id"/><br/>
</td>
</tr>
<tr>
<td>
<b><font color="red">Subject:
</td>
<td>
<input type="text" name="sub" value="Enter Subject Line"><br/>
</td>
</tr>
<tr>
<td>
<b><font color="red">Message Text:
</td>
<td>
<textarea rows="12" cols="80" name="mess"></textarea><br/>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Send">

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 22 of 25
</td>
<td>
<input type="reset" value="Reset">
</td>
</tr>
</table>
</form>
</body>
</html>

Step 6
Now create a new JSP page "mailJSP.jsp" and write the following code for it. In the comment line I'll provide you
a short description of the use of each attribute.
mailJSP.jsp
<%@ page import="java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*" %>
<%
//Creating a result for getting status that messsage is delivered or not!
String result;
// Get recipient's email-ID, message & subject-line from index.html page
final String to = request.getParameter("mail");
final String subject = request.getParameter("sub");
final String messg = request.getParameter("mess");

// Sender's email ID and password needs to be mentioned


final String from = "enter your gmail-id";
final String pass = "enter your gmail-password";

// Defining the gmail host


String host = "smtp.gmail.com";

// Creating Properties object


Properties props = new Properties();

// Defining properties
props.put("mail.smtp.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.user", from);
props.put("mail.password", pass);
props.put("mail.port", "465");

// Authorized the Session object.


Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});

try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 23 of 25
message.setSubject(subject);
// Now set the actual message
message.setText(messg);
// Send message
Transport.send(message);
result = "Your mail sent successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send mail....";
}
%>
<title>Sending Mail in JSP</title>
<h1><center><font color="blue">Sending Mail Using JSP</font></h1>
<b><center><font color="red"><% out.println(result);%></b>

Note: You need to add two JAR files, named "mail.jar" and "activation.jar" to run this app. You can
directly download this JAR file from the Oracle website.

Step 7 : Now our project is ready to run. Right-click on the "index.html" file and select "Run". The following
interface will be generated.

Step 8: Now provide the detail there as "mail-id", "subject-line" and "message-content" as in the following that I
provided.

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 24 of 25
Step 9
Click on the "send" button. The following message will be generated. If it's showing an error, in other words
something is missing, then recheck your JSP code and try again else you will get the same message as in the
following.

Step 10
For confirmation of the mail go to the receive mail inbox (those mail-ids that you provide in the sending page) or
go to your mail-id and check the sent mail items. As in the following.

--------------------------------------------------------------------------------------------------------------------------------------------

The New College (Autonomous), Chennai-14 / Department of Computer Applications – Shift – II / Dr.K.Sankar Page 25 of 25

You might also like