You are on page 1of 47

JSP (Java Server Pages)

Java Server Pages (JSP) is a technology that allows developers to create


dynamic web pages using a combination of HTML, XML, and Java
code. JSP pages are executed on a web server, and the resulting output is
sent to the client's web browser. JSP provides a way to easily access
Java code and objects from within a web page, simplifying the creation
of dynamic web pages. JSP pages are typically used in conjunction with
Java servlets, which handle data processing and client requests. JSP is
part of the Java EE platform and is supported by most web servers and
servlet containers.

https://www.w3schools.in/jsp/tutorials/
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.
The Lifecycle of a JSP Page

• The JSP pages follow these phases:


• Translation of JSP Page
• Compilation of JSP Page
• Classloading (the classloader loads class file)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( the container invokes jspInit() method).
• Request processing ( the container invokes _jspService() method).
• Destroy ( the container invokes jspDestroy() method).
• JSP page is translated into Servlet by the help of JSP translator. The
JSP translator is a part of the web server which is responsible for
translating the JSP page into Servlet. After that, Servlet page is
compiled by the compiler and gets converted into the class file.
Moreover, all the processes that happen in Servlet are performed on
JSP later like initialization, committing response to the browser and
destroy.
The Directory structure of JSP
• The directory structure of JSP page is same as Servlet. We contain the
JSP page outside the WEB-INF folder or in any directory.
Creating a JSP Page
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
Creating JSP in Eclipse IDE with Tomcat
server
• Create a Dynamic web project
• create a jsp
• start tomcat server and deploy the project
1) Create the dynamic web project

• For creating a dynamic web project click on File Menu -> New ->
dynamic web project -> write your project name e.g. first -> Finish.
2) Create the JSP file in eclipse IDE

• For creating a jsp file explore the project by clicking the + icon ->
right click on WebContent -> New -> jsp -> write your jsp file name
e.g. index -> next -> Finish.
• 3) Start the server and deploy the project:
JSP Scriptlet tag (Scripting elements)

Java provides various scripting elements that allow you to insert Java
code from your JSP code into the servlet. Scripting elements have
different components that are allowed by JSP.
Scripting Elements in JSP
• Scripting elements in JSP must be written within the <% %> tags. The
JSP engine will process any code you write within the pair of the <%
and %> tags, and any other texts within the JSP page will be treated as
HTML code or plain text while translating the JSP page.
different scripting elements
• Comment <%-- Set of comment statements --%>
• Directive <%@ directive %>
• Declaration <%! declarations %>
• Scriptlet <% scriplets %>
• Expression <%= expression %>
• Comment
• Comments are marked as text or statements that are ignored by the JSP
container. They are useful when you want to write some useful
information or logic to remember in the future.

<body> <h2>A Test of Comments</h2>

<%-- This comment will not be visible in the page source --%>
</body>
Declaration
• As the name suggests, it is used to declare methods and variables you
will use in your Java code within a JSP file. According to the rules of
JSP, any variable must be declared before it can be used.
• Jsp initializer scans the code and find the declaration tag and initializes
all the variables, methods, and classes. JSP container keeps this code
outside of the service method (_JSPService()) to make them class
level variables and methods.
<body>
<!--declaration of username variable.... -->
<%! String username=“abc"; %>

<%="Hello : "+username %>

</body>
JSP Scriplet 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
<!-- Example of JSP code which prints the Username -->
<html>
<body>
<form action=“abc.jsp">
<!-- move the control to Geeks.jsp when Submit button is click -->

Enter Username:
<input type="text" name="username">
<input type="submit" value="Submit"><br/>

</form>
</body>
</html>
• abc.jsp

<body>
<%
String name=request.getParameter("username");
out.print("Hello "+name);
%>
</body>
Expressions
• 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.
<html>
<body>
<%= Hello jsp %> <!-- Expression tag -->
</body>
</html>
JSP Directives
• Directives supply directions and messages to a JSP container. The
directives provide global information about the entire page of JSP.
Hence, they are an essential part of the JSP code.
• Directives can contain several attributes that are separated by a comma
and act as key-value pairs. In JSP, directives are described with a pair
of <%@ .... %> tags.
• The syntax of Directives looks like:

• <%@ directive attribute="" %>


There are 3 types of directives:
1.Page directive
2.Include directive
3.Taglib directive
Page Directive
• The page directive is used for defining attributes that can be applied to
a complete JSP page. You may place your code for Page Directives
anywhere within your JSP page. However, in general, page directives
are implied at the top of your JSP page.
• %@ page attribute = "attribute_value" %>
The attributes used by the Page directives are:
• buffer: Buffer attribute sets the buffer size in KB to control the JSP
page's output.
• contentType: The ContentType attribute defines the document's MIME
(Multipurpose Internet Mail Extension) in the HTTP response header.
• autoFlush: The autofill attribute controls the behavior of the servlet
output buffer. It monitors the buffer output and specifies whether the
filled buffer output should be flushed automatically or an exception
should be raised to indicate buffer overflow.
• errorPage: Defining the "ErrorPage" attribute is the correct way to
handle JSP errors. If an exception occurs on the current page, it will be
redirected to the error page.
• extends: extends attribute used for specifying a superclass that tells
whether the generated servlet has to extend or not.
• import: The import attribute is used to specify a list of packages or
classes used in JSP code, just as Java's import statement does in a Java
code.
• isErrorPage: This "isErrorPage" attribute of the Page directive is used
to specify that the current page can be displayed as an error page.
• info: This "info" attribute sets the JSP page information, which is later
obtained using the getServletInfo() method of the servlet interface.
• isThreadSafe: Both the servlet and JSP are multithreaded. If you want
to control JSP page behavior and define the threading model, you can
use the "isThreadSafe" attribute of the page directive.
• Language: The language attribute specifies the programming language
used in the JSP page. The default value of the language attribute is
"Java".
• Session: In JSP, the page directive session attribute specifies whether
the current JSP page participates in the current HTTP session.
• isELIgnored: This isELIgnored attribute is used to specify whether the
expression language (EL) implied by the JSP page will be ignored.
• isScriptingEnabled: This "isScriptingEnabled" attribute determines if
the scripting elements are allowed for use or not.
Include Directive
• The JSP "include directive" is used to include one file in another JSP
file. This includes HTML, JSP, text, and other files. This directive is
also used to create templates according to the developer's requirement
and breaks the pages in the header, footer, and sidebar.
• To use this Include Directive, you have to write it like:

• <%@ include file = "relative url" >


JSTL
(JSP Standard Tag Library)

• JavaServer Pages Tag Library (JSTL) is a set of tags that can be


used for implementing some common operations such as looping,
conditional formatting, and others.

• To enable JSTL features, we’d have to add the library to our project.
For a Maven project, we add the dependency in pom.xml file:
• With the library added to our project, the final setup will be to add
the core JSTL tag and any other tags’ namespace file to our JSP
using the taglib directive like this:
• <%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
• JSTL Core Tags
• The JSTL core tag provides variable support, URL management,
flow control etc. The syntax used for including JSTL core library in
your JSP is:
• <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
c:out It display the result of an expression, similar to the way <%=...%> tag
work.

c:import It Retrives relative or an absolute URL and display the contents to


either a String in 'var',a Reader in 'varReader' or the page.

c:set It sets the result of an expression under evaluation in a 'scope' variable.

c:remove It is used for removing the specified scoped variable from a particular
scope.

c:catch It is used for Catches any Throwable exceptions that occurs in the body.

c:if It is conditional tag used for testing the condition and display the body
content only if the expression evaluates is true.
c:choose, c:when, c:otherwise It is the simple conditional tag that includes its body content if
the evaluated condition is true.

c:forEach It is the basic iteration tag. It repeats the nested body content
for fixed number of times or over collection.

c:forTokens It iterates over tokens which is separated by the supplied


delimeters.

c:param It adds a parameter in a containing 'import' tag's URL.

c:redirect It redirects the browser to a new URL and supports the context-
relative URLs.

c:url It creates a URL with optional query parameters.


• Exception Handling
• The exception is normally an object that is thrown at runtime.
Exception Handling is the process to handle the runtime errors. There
may occur exception any time in your web application. So handling
exceptions is a safer side for the web developer. In JSP, there are two
ways to perform exception handling:
1.By errorPage and isErrorPage attributes of page directive
2.By <error-page> element in web.xml file
There are 3 files:
•index.jsp for input values
•process.jsp for dividing the two numbers and displaying the result
•error.jsp for handling the exception
•Index.jsp

1.<form action="process.jsp">
2.No1:<input type="text" name="n1" /><br/><br/>
3.No1:<input type="text" name="n2" /><br/><br/>
4.<input type="submit" value="divide"/>
5.</form>
•Process.jsp
1. <%@ page errorPage="error.jsp" %>
2. <%
3.
4. String num1=request.getParameter("n1");
5. String num2=request.getParameter("n2");
6.
7. int a=Integer.parseInt(num1);
8. int b=Integer.parseInt(num2);
9. int c=a/b;
10.out.print("division of numbers is: "+c);
11.
12.%>
•error.jsp
1. <%@ page isErrorPage="true" %>
2.
3. <h3>Sorry an exception occured!</h3>
4.
5. Exception is: <%= exception %>

You might also like