0% found this document useful (0 votes)
17 views

JSP Complete

The document discusses Java Server Pages (JSP) technology. Some key points: - JSP is used to create dynamic web applications and is easier to maintain than servlets. It allows mixing Java code and HTML. - JSP enables separating presentation logic from business logic - web designers can update JSP pages while Java developers write server-side code. - A JSP page is a text document that can return static and dynamic content. Its lifecycle involves translation to a servlet, compilation, loading, and execution. - JSP provides scripting elements like scriptlets, expressions, and directives to embed Java code in HTML pages. Implicit objects, actions, and EL can also be

Uploaded by

Esha Faisal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

JSP Complete

The document discusses Java Server Pages (JSP) technology. Some key points: - JSP is used to create dynamic web applications and is easier to maintain than servlets. It allows mixing Java code and HTML. - JSP enables separating presentation logic from business logic - web designers can update JSP pages while Java developers write server-side code. - A JSP page is a text document that can return static and dynamic content. Its lifecycle involves translation to a servlet, compilation, loading, and execution. - JSP provides scripting elements like scriptlets, expressions, and directives to embed Java code in HTML pages. Implicit objects, actions, and EL can also be

Uploaded by

Esha Faisal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Java Server Pages

(JSP)
Java Server Pages (JSP)

▪ JSP technology is used to create dynamic web


applications.

▪ JSP pages are easier to maintain than a Servlet.


▪ JSP pages are opposite of Servlets as a servlet
adds HTML code inside Java code, while JSP adds
Java code inside HTML using JSP tags.
Java Server Pages (JSP)

▪ JSP enables us to write HTML pages containing tags,


inside which we can include powerful Java programs.

▪ Using JSP, one can easily separate Presentation and


Business logic, as a web designer can design and update
JSP pages creating the presentation layer and java
developer can write server side complex computational
code without concerning the web design.

▪ And both the layers can easily interact over HTTP


requests.
What is a JSP Page?

▪ A text-based document capable of returning both static


and dynamic content to a client browser. Static content
and dynamic content can be intermixed.

▪ Static content
– HTML, XML, Text

▪ Dynamic content
– Java code
– Displaying properties of JavaBeans
– Invoking business logic defined in Custom tags
Advantages of JSP over Servlet?

▪ Extension to Servlet
▪ JSP technology is the extension to servlet technology. We
can use all the features of servlet in JSP. In addition to, we
can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP
development easy.

▪ Easy to maintain
▪ JSP can be easily managed because we can easily separate
our business logic with presentation logic. In servlet
technology, we mix our business logic with the
presentation logic.
Advantages of JSP over Servlet?

▪ Fast Development: No need to recompile and redeploy


▪ If JSP page is modified, we don't need to recompile and
redeploy the project. The servlet code needs to be
updated and recompiled if we have to change the look
and feel of the application.

▪ Less code than Servlet


▪ In JSP, we can use a lot of tags such as action tags,
custom tags etc. that reduces the code. Moreover, we
can use EL, implicit objects etc.
JSP Architecture
Life Cycle of a JSP Page
Life Cycle of a JSP Page

▪ 1) Browser sends an HTTP request to the web server.


▪ 2) The web server recognizes that the HTTP request is for a JSP
page (with .jsp) and forwards it to a JSP engine.
▪ 3) The JSP engine loads the JSP page from disk and converts it into
a servlet.
▪ 4) The JSP engine compiles the servlet into an executable class and
forwards the original request to a servlet engine.
▪ 5) Servlet engine loads the Servlet class and executes it, produces
an output in HTML format, which the servlet engine passes to the
web server inside an HTTP response.
▪ 6) The web server forwards the HTTP response to your browser in
terms of static HTML content.
▪ 7) Finally web browser handles the dynamically generated HTML
page inside the HTTP response exactly as if it were a static page.
JSP Page Lifecycle Phases

▪ Translation of JSP Page - (Translate JSP (.jsp) to (.java)) Servlet)


▪ Compilation of JSP Page - (Servlet (.java) Compilation to Bytecode(.class))
▪ Classloading - (class file is loaded by the classloader)
▪ Instantiation (Object of the Generated Servlet is created)
▪ Execution Phase
❑ Initialization (jspInit() method is invoked by the container)

❑ Reqeust processing (_jspService() method is invoked by the container)

❑ Destroy (jspDestroy() method is invoked by the container)


JSP Page Lifecycle Methods during Execution Phase
JSP

▪ JSP Scripting Elements


▪ Implicit Objects
▪ JSP Standard Actions
▪ Expression Language
▪ MVC in JSP
▪ JSTL
JSP Scripting Elements

▪ The scripting elements provides the ability to insert java


code inside the jsp. There are five types of scripting
elements:

▪ Comments tag
▪ Declaration tag
▪ Expression tag
▪ Scriptlet tag
▪ Directive Tag
JSP Scripting Elements – Comments

▪ JSP comment marks text or statements that the JSP


container should ignore. A JSP comment is useful when
you want to hide or "comment out" part of your JSP
page. Following is the syntax of JSP comments:

<html> <body>
A Test of Comments
<%-- comment not be visible in the page --%>
</body> </html>
JSP Scripting Elements – Declaration

▪ Declaration Tag: used to declare variables and methods.


The code written inside JSP declaration tag is placed
outside the service() method of auto generated servlet.
So, it doesn't get memory at each request.
<html> <body>
<%! int cube(int n){ return n*n*n;} %>
<%! int data = 50; %>
<%= "Value of the variable is:"+ data %>
</body>
</html>
JSP Scripting Elements – Expression

▪ Expression Tag: is written to the output stream of the


response. So, you need not write out.print() to write
data. It is mainly used to print the values of variable or
method.

<html>
<body>
<%= request.getParameter("uname") %>
</body>
</html>
JSP Scripting Elements – Scriptlet
▪ Scriptlet tag: is used to execute java source code in JSP.
Scriptlet tag can only declare variables not methods.
The declaration of scriptlet code is placed inside
_jspService() method. So, it get memory at each
request.
<html> <body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</body>
</html>
JSP Directives

▪ The jsp directives are messages that tells the web container
how to translate a JSP page into the corresponding servlet.

▪ Three types of directives:


❑ page directive
❑ include directive
❑ taglib directive

▪ Syntax of JSP Directive


❑ <%@directive attribute = "value" %>
JSP Page Directive

▪ The page directive defines attributes that apply to an entire


JSP page.
▪ Syntax of JSP page directive
❑ <%@ page attribute="value" %>

▪ Attributes of JSP page directive


- import - contentType
- extends - info
- buffer - language
- isELIgnored - isThreadSafe
- autoFlush - session
- pageEncoding - errorPage
- isErrorPage
JSP Page Directive
Attribute Purpose
buffer Specifies a buffering model for the output stream.
autoFlush Controls the behavior of the servlet output buffer.
contentType Defines the character encoding scheme.
errorPage Defines the URL of another JSP that reports on Java unchecked runtime
exceptions.
isErrorPage Indicates if this JSP page is a URL specified by another JSP page's errorPage
attribute.
extends Specifies a superclass that the generated servlet must extend
import Specifies a list of packages or classes for use in the JSP as the Java import
statement does for Java classes.
info Defines a string that can be accessed with the servlet's getServletInfo() method.
isThreadSafe Defines the threading model for the generated servlet.
language Defines the programming language used in the JSP page.
session Specifies whether or not the JSP page participates in HTTP sessions
isELIgnored Specifies whether or not EL expression within JSP page will be ignored.
isScriptingEnabled Determines if scripting elements are allowed for use.

Details of few page directives is on next slides.


JSP Page Directive – import

▪ The import attribute is used to import class, interface


or all the members of a package. It is similar to
import keyword in java class or interface.

▪ Example:
<%@ page import = "java.util.Date" %>
<html>
<body>
Today is: <%= new Date() %>
</body>
</html>
JSP Page Directive – contentType

▪ The contentType attribute defines the MIME (Multipurpose


Internet Mail Extension) type of the HTTP response. The default
value is "text/html; charset=ISO-8859-1".

▪ Example:
<%@ page contentType = “application/msword” %>
OR
<%@ page contentType = “text/html” %>
<html>
<body> My Page </body>
</html>
JSP Page Directive – info

▪ This attribute sets information of the JSP page which is retrieved


later by using getServletInfo() method of Servlet interface.

<%@ page info=“Copy Right 2017 " %>


<html>
<body> Page information is <%= getServletInfo %> </body>
</html>

The web container create a method getServletInfo() in the resulting


servlet. For example:

public String getServletInfo() {


return “Copy Right 2017";
}
JSP Page Directive – buffer

▪ The buffer attribute sets the buffer size in kilobytes to handle


output generated by the JSP page. The default size of the buffer is
8Kb.

<%@ page buffer="16kb" %>

<html>
<body> My Page </body>
</html>
JSP Page Directive – language

▪ The language attribute specifies the scripting language used in the


JSP page. The default value is "java".

<%@ page language = “java” %>

<html>
<body> My Page </body>
</html>
JSP Page Directive – isELIgnored

▪ To ignore the Expression Language (EL) in JSP by the isELIgnored


attribute. By default its value is false i.e. Expression Language is
enabled by default. We see Expression Language later

<%@ page isELIgnored = “true" %>

<html>
<body>
EL expression result is: ${2 * 4 + 3 * 4}
</body>
</html>
JSP Page Directive – isThreadSafe

▪ Servlet and JSP both are multithreaded. If you want to control this
behaviour of JSP page, you can use isThreadSafe attribute of page
directive. The default value of isThreadSafe value is true. If you
make it false, the web container will serialize the multiple requests,
i.e. it will wait until the JSP finishes responding to a request before
passing another request to it. If you make the value of isThreadSafe
attribute like:

<%@ page isThreadSafe="false" %>

<html>
<body> My Page </body>
</html>
JSP Page Directive – errorPage

▪ The errorPage attribute is used to define the error page, if


exception occurs in the current page, it will be redirected
to the error page.
// JSP code to divide two numbers
<% @page errorPage = "error.jsp" %> < %
String num1 = request.getParameter("first");
String num2 = request.getParameter("second");
int x = Integer.parseInt(num1);
int y = Integer.parseInt(num2);
int z = x / y; // dividing the numbers
out.print("division of numbers is: " + z); // result
%>
JSP Page Directive – isErrorPage

▪ The isErrorPage attribute is used to declare that the


current page is the error page. The exception object can
only be used in the error page.

<%@page isErrorPage = “true" %>

<html>
<body> Sorry an Exception Occurred
The exception is: <%= exception %>
</body>
</html>
JSP Page buffer and autoflush

▪ By default the buffer is 8kb big. The following example


tries asks the browser to redirect to another JSP page.
Less than 8kb of bytes were written, so the buffer was
not flushed. Redirection succeeds.
JSP Page buffer and autoflush

▪ By default, the buffer is 8kb big. The following examples


writes more than 8kb of data and redirectiong will fail.
A java.lang.IllegalStateException will be thrown.
Summary of JSP Page Directive Attributes
JSP Include Directive

▪ The include directive is used to include the contents of


any resource it may be jsp file, html file or text file. The
include directive includes the original content of the
included resource at page translation time (the jsp page is
translated only once so it will be better to include static
resource).

<%@include file = "header.html" %>

<html>
<body> My Page </body>
</html>
JSP Include Action

The include action allows you to include either a static


or dynamic resource in a JSP file. The results of
including static and dynamic resources are quite
different. If the resource is static, its content is
directly inserted into the calling JSP file. If the
resource is dynamic, the request is sent to the
included resource, the included page is executed, and
then the result is included in the response from the
calling JSP page.
Advantages of JSP Custom Tags

▪ Definition: Custom tags are user defined tags.


▪ Eliminates the need of scriptlet tag Scriptlet is
considered bad programming approach in JSP. So, the
custom tags eliminates the need of scriptlet tag

▪ Separation of business logic from JSP The custom tags


separate the business logic from the JSP page so that it
may be easy to maintain.

▪ Re-usability The custom tags makes the possibility to


reuse the same business logic again and again.
Steps to Create Custom Tags

▪ Create the Tag handler class


❑ In this class, we specify what our custom tag will do when it is
used in a JSP page. and perform action at the start or at the end
of the tag.
▪ Create the Tag Library Descriptor (TLD) file
❑ Tag descriptor file where we will specify our tag name, tag
handler class and tag attributes.
▪ Create the JSP file that uses the Custom tag defined in the TLD file
❑ A JSP page where we will be using our custom tag.
Create the Tag handler class

▪ To create the Tag Handler, we are inheriting the TagSupport


class and overriding its method doTag().

▪ To write data for the jsp, we need to use the JspWriter class.
▪ The PageContext class provides getOut() method that returns
the instance of JspWriter class.

▪ TagSupport class provides instance of pageContext by default.


Create the Tag handler class

package myJSP.com;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {

/*This is just to display a message, when we will use our custom tag.
This message would be displayed */
JspWriter out = getJspContext().getOut();
out.println("Hello Custom Tag!");
}
}
Create the Tag Library Descriptor (TLD)

▪ Tag Library Descriptor (TLD) file contains information of tag and Tag
Hander classes.
▪ It must be contained inside the WEB-INF directory.
▪ Should have a .tld extension.

▪ <name> tag: custom tag name.


❑ In this example we have given it as MyMsg

▪ <tag-class> tag: Fully qualified class name.


❑ Our tag handler HelloTag.class is in package com so we have
given the value as com.HelloTag.
Create the Tag Library Descriptor (TLD)
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>

<uri>/WEB-INF/custom</uri>
<tag>
<name>MyMsg</name>
<tag-class>com.HelloTag</tag-class>
</tag>
</taglib>
Using custom tag in JSP

▪ taglib directive should have the TLD file path in uri field.
▪ We have created message.tld file so we have given the path
of that file.

▪ Choose any prefix and specify it in taglib directive’s prefix


field. Here we have specified it as myprefix.
❑ <prefix:tagName/>.

❑ Our prefix is myprefix and tag name is MyMsg so we


have called it as <myprefix:MyMsg/> in the below JSP
page.
Using custom tag in JSP

<%@ taglib prefix="myprefix" uri="/WEBINF/message.tld"%>

<html>
<head>
<title>Custom Tags in JSP Example</title>
</head>
<body>
<myprefix:MyMsg/>
</body>
</html>
JSP Implicit Objects

▪ There are 9 jsp implicit objects. These objects are created by the
web container that are available to all the JSP pages.

Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
JSP Implicit Object – out

▪ For writing any data to the buffer, JSP provides an implicit


object named out. It is the object of JspWriter. In case of
servlet you need to write:
PrintWriter out = response.getWriter();

<html> <body>
<% out.print(“Welcome JSP”); %>
</body>
</html>
JSP Implicit Object – request

▪ JSP request is an implicit object of type


HttpServletRequest i.e. created for each JSP request by
the web container.

▪ It can be used to get request information such as


parameter, header information, remote address, server
name, server port, content type, character encoding etc.

▪ It can also be used to set, get and remove attributes from


the JSP request scope
JSP Implicit Object – request

<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
=================================
<%
String name = request.getParameter("uname");
out.print("welcome "+name);
%>
JSP Implicit Object – response

▪ response implicit object of type HttpServletResponse.

▪ The instance of HttpServletResponse is created by the


web container for each JSP request.

▪ It can be used to add or manipulate response such as


redirect response to another resource, send error etc.
JSP Implicit Object – response

▪ <form action="welcome.jsp">
▪ <input type="text" name="uname">
▪ <input type="submit" value="go"><br/>
▪ </form>
<%
response.sendRedirect("http://www.google.com");
%>
JSP Implicit Object – config

▪ In JSP, config is an implicit object of type ServletConfig.


▪ This object can be used to get initialization parameter for
a particular JSP page from web.xml file.

▪ The config object is created by the web container for each


JSP page.
JSP Implicit Object – config
<form action="welcome"> <input type="text" name="uname">
<input type="submit" value="go"><br/> </form>
================================
<web-app> <servlet>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet> </web-app>
================================
<% out.print("Welcome"+request.getParameter("uname"));
String driver = config.getInitParameter("dname");
out.print("driver name is="+ driver); %>
JSP Implicit Object – exception

▪ In JSP, exception is an implicit object of type


java.lang.Throwable class.
▪ This object can be used to print the exception. But it can
only be used in error pages.
▪ Example:
<%@page isErrorPage="true" %>
<html> <body>
Sorry following exception occured:<%= exception %>
</body> </html>
JSP Standard Actions
▪ There are many JSP action tags or elements.
▪ Each JSP action tag is used to perform some specific tasks.
▪ The action tags are used to control the flow between
page.
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and
include mostly.
jsp:fallback can be used to print the message if plugin is working. It
is used in jsp:plugin.
jsp:forward action tag

▪ The jsp:forward action tag is used to forward the request


to another resource it may be jsp, html or another
resource
<html> <body>
<h2>This is index page</h2>
<jsp:forward page="printdate.jsp" />
</body> </html>
==============================
<html> <body>
<% out.print(“This is forwarded printdate.jsp page”); %>
</body> </html>
jsp:include action tag

▪ The jsp:include action tag is used to include the content of another


resource it may be JSP, HTML or Servlet.

▪ The jsp include action tag includes the resource at request time so
it is better for dynamic pages because there might be changes in
future.

▪ The jsp:include tag can be used to include static as well as dynamic


pages.
JSP include directive JSP include action
includes resource at includes resource at request
translation time. time.
better for static pages. better for dynamic pages.
includes the original content calls the include method.
in the generated servlet.

You might also like