[go: up one dir, main page]

0% found this document useful (0 votes)
6 views16 pages

U3_JSP 1

Java Server Pages (JSP) is a server-side technology used for creating dynamic web applications by embedding Java code within HTML pages. JSP offers advantages over Servlets, such as easier maintenance, no recompilation, and reduced coding effort, while also providing features like implicit objects and various JSP elements. The JSP lifecycle involves translation to a servlet, compilation, and request processing, making it an efficient way to generate dynamic content for web applications.

Uploaded by

harshitaswork06
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)
6 views16 pages

U3_JSP 1

Java Server Pages (JSP) is a server-side technology used for creating dynamic web applications by embedding Java code within HTML pages. JSP offers advantages over Servlets, such as easier maintenance, no recompilation, and reduced coding effort, while also providing features like implicit objects and various JSP elements. The JSP lifecycle involves translation to a servlet, compilation, and request processing, making it an efficient way to generate dynamic content for web applications.

Uploaded by

harshitaswork06
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/ 16

Introduction to JSP

In Java, JSP stands for Java Server Pages. It is a server-side technology which is used for creating
web applications. It is used to create dynamic web content. JSP consists of both HTML tags and JSP
tags. In this, JSP tags are used to insert JAVA code into HTML pages. It is an advanced version
of Servlet Technology i.e. 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 the JSP container before processing the client’s request. JSP has
various features like JSP Expressions, JSP tags, JSP Expression Language, etc.
How JSP more advantageous than Servlet?
 They are easy to maintain.
 No recompilation or redeployment is required.
 Less coding is required in JSP.
 JSP has access to the entire API of JAVA.
 JSP are extended version of Servlet.
Features of JSP
 Coding in JSP is easy : As it is just adding JAVA code to HTML/XML.
 Reduction in the length of Code : In JSP we use action tags, custom tags etc.
 Connection to Database is easier : It is easier to connect website to database and allows to read
or write data easily to the database.
 Make Interactive websites : In this we can create dynamic web pages which helps user to
interact in real time environment.
 Portable, Powerful, flexible and easy to maintain : as these are browser and server
independent.
 No Redeployment and No Re-Compilation : It is dynamic, secure and platform independent so
no need to re-compilation.
 Extension to Servlet : as it has all features of servlets, implicit objects and custom tags
1. Declaration Tag : It is used to declare variables.
2. Java Scriplets : It allows us to add any number of JAVA code, variables and expressions.
3. JSP Expression : It evaluates and convert the expression to a string.
4. JAVA Comments : It contains the text that is added for information which has to be ignored.
 Create html page from where request will be sent to server eg try.html.
 To handle to request of user next is to create .jsp file Eg. new.jsp
 Create project folder structure.
 Create XML file eg my.xml.
 Create WAR file.
 Start Tomcat
 Run Application
5. It does not require advanced knowledge of JAVA
6. It is capable of handling exceptions
7. Easy to use and learn
8. It contains tags which are easy to use and understand
9. Implicit objects are there which reduces the length of code
10. It is suitable for both JAVA and non JAVA programmer
11. Difficult to debug for errors.
12. First time access leads to wastage of time
13. It’s output is HTML which lacks features.
Creating a simple JSP Page
hello.JSP :
JSP simply puts Java inside HTML pages. You can take any existing HTML page and change its
extension to “.jsp” instead of “.html”. In fact, this is the perfect exercise for your first JSP.
Take the HTML file you used in the previous exercise. change its extension from “.html” to “jsp”.
Now load the new file, with the “.jsp” extension, in your browser.

Play
Unmute

You will see the same output, but it will take longer! But only the first time. If you reload it again, it
will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java file, compiled, and
loaded. This compilation only happens once, so after the first load, the file doesn’t take long to load
anymore. (But every time you change the JSP file, it will be re-compiled again.)
Of course, it is not very useful to just write HTML pages with a .jsp extension! We now proceed to
see what makes JSP so useful.
Adding dynamic content via expressions:
As we saw in the previous section, any HTML file can be turned into a JSP file by changing its
extension to .jsp . Of course , what makes JSP useful is the ability to embed Java. Put the following
text in a file. jsp extension (let us call it hello.jsp) , place it in your JSP directory, and view it in a
browser.
<HTML>
<BODY>
<% out.print(“ Hello! The time is now <%= new java.util.Date();”)%>
</BODY>
</HTML>

Notice that each time you reload the page in the browser, it comes up with the current time. The
character sequence.
<%= and %> enclose Java expressions, which are evaluated at run time.
This is what makes it possible to use JSP to generate dynamic HTML pages that change in response
to user actions or vary from user to user.
Explain JSP Elements:
We will learn about the various elements available in JSP with suitable examples. In JSP elements
can be divided into 4 different types.
These are:
 Expression
 Scriplets
 Directives
 Declarations
Expression:
We can use this tag to output any data on the generated page. These data are automatically
converted to string and printed on the output stream.
Syntax:
JSP Expressions are : <%="Anything" %>

NOTE : JSP Expressions start with Syntax of JSP Scriptles are with <%=and ends with
%>. Between these, you can put anything that will convert to the String and that will be displayed.
Example:
<%="HelloWorld!" %>

Scriplets:
In this tag we can insert any amount of valid java code and these codes are placed in the _jsp
Service method by the JSP engine.
Syntax:
<%//java codes%>
NOTE : JSP Scriptlets begins with <% and ends %> . We can embed any amount of Java code in
the JSP Scriptlets. JSP Engine places these codes in the _jspService() method.
Variables available to the JSP Scriptlets are:
 Request
 Response
 Session
 Out
Directives:
A JSP “directive” starts with <%@ characters. In the directives, we can import packages , and
define error-handling pages or the session information of the JSP page.
Syntax:
<%@directive attribute="value"% >

 page
 include
 taglib
Declarations :
This tag is used for defining the functions and variables to be used in the JSP.
Syntax:
<%!
//java codes
%>
NOTE : JSP Declaratives begins with <%! and ends %> with We can embed any amount of java
code in the JSP Declaratives. Variables and functions defined in the declaratives are class-level and
can be used anywhere on the JSP page.
Example :
<%@page import="java.util.*"%>
<HTML>
<BODY>
<%!
Date the Date=new Date(); Date getDate()
{
System.out.println("In getDate() method"); return theDate;
}
%>
Hello! The time is now<%=getDate()%>
</BODY>
</HTML

Example of a JSP Web Page:


<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>
<BODY>
<%out.println("Hello there!");%>
</BODY>
</HTML>

Run a Simple JSP Page:


Step-1: Save the JSP file using “.jsp” extension (ex- “hello.jsp”)
Step-2: Start the server
Step-3: Place your application inside a folder
Step-4: To execute the JSP script, simply start tomcat server and use a browser to browse an URL
of the JSP page i.e.
http://localhost:portnumber/YourApplicationContextRoot/jspfile then you will see the jsp file is
being compiled.
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.

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. JSP Processing is illustrated and
discussed in sequential steps prior to which a pictorial media is provided as a handful
pick to understand the JSP processing better which is as follows:
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.

Life cycle of JSP


A Java Server Page life cycle is defined as the process that started with its creation which later
translated to a servlet and afterward servlet lifecycle comes into play. This is how the process goes
on until its destruction.
Lifecycle of JSP

Following steps are involved in the JSP life cycle:


1. Translation of JSP page to Servlet
2. Compilation of JSP page(Compilation of JSP into test.java)
3. Classloading (test.java to test.class)
4. Instantiation(Object of the generated Servlet is created)
5. Initialization(jspInit() method is invoked by the container)
6. Request processing(_jspService()is invoked by the container)
7. JSP Cleanup (jspDestroy() method is invoked by the container)
We can override jspInit(), jspDestroy() but we can’t override _jspService() method.
Translation of JSP page to Servlet:
This is the first step of the JSP life cycle. This translation phase deals with the Syntactic correctness
of JSP. Here test.jsp file is translated to test.java.
1. Compilation of JSP page: Here the generated java servlet file (test.java) is compiled to a class
file (test.class).
2. Classloading: The classloader loads the Java class file into the memory. The loaded Java class
can then be used to serve incoming requests for the JSP page.
3. Instantiation: Here an instance of the class is generated. The container manages one or more
instances by providing responses to requests.
4. Initialization: jspInit() method is called only once during the life cycle immediately after the
generation of the Servlet instance from JSP.
5. Request processing: _jspService() method is used to serve the raised requests by JSP. It takes
request and response objects as parameters. This method cannot be overridden.
6. JSP Cleanup: In order to remove the JSP from the use by the container or to destroy the method
for servlets jspDestroy()method is used. This method is called once, if you need to perform any
cleanup task like closing open files, or releasing database connections jspDestroy() can be
overridden.
Difference between Servlet and JSP

Brief Introduction: Servlet technology is used to create a web application. A servlet is a Java class
that is used to extend the capabilities of servers that host applications accessed by means of a request-
response model. Servlets are mainly used to extend the applications hosted by web services.
JSP is used to create web applications just like Servlet technology. A JSP is a text document that
contains two types of text: static data and dynamic data. The static data can be expressed in any text-
based format (like HTML, XML, SVG, and WML), and the dynamic content can be expressed by
JSP elements. 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 compilation code.

Writing code for servlet is harder than JSP as it is


JSP is easy to code as it is java in HTML.
HTML in java.

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

JSP is slower than Servlet because the first step


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

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

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

In Servlet by default session management is not In JSP session management is automatically


enabled, user have to enable it explicitly. enabled.

In Servlet we have to implement everything like In JSP business logic is separated from
business logic and presentation logic in just one presentation logic by using JavaBeansclient-
servlet file. side.

Modification in Servlet is a time-consuming


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

It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.

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

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

It cannot handle extensive data processing very


It can handle extensive data processing.
efficiently.

The facility of writing custom tags is not present. The facility of writing custom tags is present.

Before the execution, JSP is compiled in Java


Servlets are hosted and executed on Web Servers. Servlets and then it has a similar lifecycle as
Servlets.

JSP Implicit object?


 JSP implicit objects are created during the translation phase of JSP to the servlet.
 These objects can be directly used in scriplets that go in the service method.
 They are created by the container automatically, and they can be accessed using objects.

There are 9 types of implicit objects available in the container:


1. Out
2. Request
3. Response
4. Config
5. Application
6. Session
7. PageContext
8. Page
9. Exception

1. Out
Out is one of the implicit objects to write the data to the buffer and send output to the client in
response
 Out object allows us to access the servlet’s output stream
 Out is object of javax.servlet.jsp.jspWriter class
 While working with servlet, we need a printwriter object
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Implicit Guru JSP1</title>
</head>
<body>
<% int num1=10;int num2=20;
out.println("num1 is " +num1);
out.println("num2 is "+num2);
%>
</body>
</html>
Explanation of the code:
Code Line 11-12– out is used to print into output stream
When we execute the above code, we get the following output:
Output:
 In the output, we get the values of num1 and num2

2. Request
 The request object is an instance of java.servlet.http.HttpServletRequest and it is one of the argument
of service method
 It will be created by container for every request.
 It will be used to request the information like parameter, header information , server name, etc.
 It uses getParameter() to access the request parameter.
Example:
Implicit_jsp2.jsp(form from which request is sent to guru.jsp)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Implicit Guru form JSP2</title>
</head>
<body>
<form action="guru.jsp">
<input type="text" name="username">
<input type="submit" value="submit">
</form>
</body>
</html>
Guru.jsp (where the action is taken)

Explanation of code:
Code Line 10-13 : In implicit_jsp2.jsp(form) request is sent, hence the variable username is processed and
sent to guru.jsp which is action of JSP.
Guru.jsp
Code Line10-11: It is action jsp where the request is processed, and username is taken from form jsp.
When you execute the above code, you get the following output
Output:
When you write test and click on the submit button, then you get the following output “Welcome Test.”

3. Response
“Response” is an instance of class which implements HttpServletResponse interface
Container generates this object and passes to _jspservice() method as parameter
“Response object” will be created by the container for each request.
It represents the response that can be given to the client
The response implicit object is used to content type, add cookie and redirect to response page
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Implicit Guru JSP4</title>
</head>
<body>
<%response.setContentType("text/html"); %>
</body>
</html>
Explanation of the code:
Code Line 11: In the response object we can set the content type
Here we are setting only the content type in the response object. Hence, there is no output for this.

4. Config
“Config” is of the type java.servlet.servletConfig
It is created by the container for each jsp page
It is used to get the initialization parameter in web.xml
Example:
Web.xml (specifies the name and mapping of the servlet)
Implicit_jsp5.jsp (getting the value of servlet name)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Implicit Guru JSP5</title>
</head>
<body>
<% String servletName = config.getServletName();
out.println("Servlet Name is " +servletName);%>
</body>
</html>
Explanation of the code:
In web.xml
Code Line 14-17: In web.xml we have mapping of servlets to the classes.
Implicit_jsp5.jsp
Code Line 10-11: To get the name of the servlet in JSP, we can use config.getServletName, which will help
us to get the name of the servlet.
When you execute the above code you get the following output:

Output:
 Servlet name is “GuruServlet” as the name is present in web.xml

5.Application
 Application object (code line 10) is an instance of javax.servlet.ServletContext and it is used to get
the context information and attributes in JSP.
Application object is created by container one per application, when the application gets deployed.
Servletcontext object contains a set of methods which are used to interact with the servlet
container.We can find information about the servlet container
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Implicit JSP6</title>
</head>
<body>
<% application.getContextPath(); %>
</body>
</html>
Explanation of the code:
 In the above code, application attribute helps to get the context path of the JSP page.

6. Session
 The session is holding “httpsession” object(code line 10).
 Session object is used to get, set and remove attributes to session scope and also used to get session
information
Example:
Implicit_jsp7(attribute is set)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Implicit JSP</title>
</head>
<body>
<% session.setAttribute("user","GuruJSP"); %>
<a href="implicit_jsp8.jsp">Click here to get user name</a>
</body>
</html>
Implicit_jsp8.jsp (getAttribute)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>implicit Guru JSP8</title>
</head>
<body>
<% String name = (String)session.getAttribute("user");
out.println("User Name is " +name);
%>
</body>
</html>
Explanation of the code:
Implicit_jsp7.jsp
Code Line 11: we are setting the attribute user in the session variable, and that value can be fetched from
the session in whichever jsp is called from that (_jsp8.jsp).
Code Line 12: We are calling another jsp on href in which we will get the value for attribute user which is
set.
Implicit_jsp8.jsp
Code Line 11: We are getting the value of user attribute from session object and displaying that value
When you execute the above code, you get the following output:
When you click on the link for the username. You will get the following output.

Output:
 When we click on link given in implicit_jsp7.jsp then we are redirected to second jsp page, i.e
(_jsp8.jsp) page and we get the value from session object of the user attribute (_jsp7.jsp).

7. PageContext
 This object is of the type of pagecontext.
 It is used to get, set and remove the attributes from a particular scope
Scopes are of 4 types:
 Page
 Request
 Session
 Application
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Implicit Guru JSP9</title>
</head>
<body>
<% pageContext.setAttribute("student","gurustudent",pageContext.PAGE_SCOPE);
String name = (String)pageContext.getAttribute("student");
out.println("student name is " +name);
%>
</body>
</html>
Explanation of the code:
Code Line 11: we are setting the attribute using pageContext object, and it has three parameters:
 Key
 Value
 Scope
In the above code, the key is student and value is “gurustudent” while the scope is the page scope. Here the
scope is “page” and it can get using page scope only.
Code Line 12: We are getting the value of the attribute using pageContext
When you execute the above code, you get the following output:
Output:
 The output will print “student name is gurustudent”.

8. Page
 Page implicit variable holds the currently executed servlet object for the corresponding jsp.
 Acts as this object for current jsp page.
Example:
In this example, we are using page object to get the page name using toString method
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Implicit Guru JSP10</title>
</head>
<body>
<% String pageName = page.toString();
out.println("Page Name is " +pageName);%>
</body>
</html>
Explanation of the code:
Code Line 10-11: In this example, we are trying to use the method toString() of the page object and trying
to get the string name of theJSP Page.
When you execute the code you get the following output:

Output:
 Output is string name of above jsp page

9. Exception
 Exception is the implicit object of the throwable class.
 It is used for exception handling in JSP.
 The exception object can be only used in error pages.Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isErrorPage="true"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Implicit Guru JSP 11</title>
</head>
<body>
<%int[] num1={1,2,3,4};
out.println(num1[5]);%>
<%= exception %>
</body>
</html>
Explanation of the code:
Code Line 10-12 – It has an array of numbers, i.e., num1 with four elements. In the output, we are trying to
print the fifth element of the array from num1, which is not declared in the array list. So it is used to get
exception object of the jsp.
Output:

We are getting ArrayIndexOfBoundsException in the array where we are getting a num1 array of the fifth
element.

You might also like