U3_JSP 1
U3_JSP 1
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
Servlet JSP
Servlet plays a controller role in the ,MVC JSP is the view in the MVC approach for
approach. showing output.
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 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.
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 )
The facility of writing custom tags is not present. The facility of writing custom tags is present.
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.