JSP
JSP
JSP
• JSP technology is used to create web application just like Servlet technology. It can
be thought of as an extension to servlet because it provides more functionality than
servlet such as expression language, jstl etc.
• 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 Tag etc.
Why Use JSP?
Java Server Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But JSP offer several advantages in comparison with
the CGI.
•Performance is significantly better because JSP allows embedding Dynamic Elements
in HTML Pages itself instead of having a separate CGI files.
•JSP are always compiled before it's processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
…
• Java Server Pages are built on top of the Java Servlets API, so like Servlets, JSP also
has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP
etc.
• JSP pages can be used in combination with servlets that handle the business logic,
the model supported by Java servlet template engines.
• Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the
most complex and demanding
Advantages of JSP
• vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is
written in Java, not Visual Basic or other MS specific language, so it is more powerful and
easier to use. Second, it is portable to other operating systems and non-Microsoft Web
servers.
• vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have
plenty of println statements that generate the HTML.
• vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real"
programs that use form data, make database connections, and the like.
• vs. JavaScript: JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and image
processing etc.
• vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
Advantage of JSP over Servlet
1) 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.
2) 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
3) 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.
4) Less code than Servlet
•In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces
the code. Moreover, we can use EL, implicit objects etc.
JSP - Architecture
Life cycle of a JSP Page
JSP Interface
JSP Processing:
• As with a normal page, your browser sends an HTTP request to the web server.
• The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine.
• This is done by using the URL or JSP page which ends with .jsp instead of .html.
• The JSP engine loads the JSP page from disk and converts it into a servlet content.
• This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code that implements the
corresponding dynamic behavior of the page.
…
• The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
• A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format, which
the servlet engine passes to the web server inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static HTML
content.
• Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
EG
Methods of Jsp Page interface
EG:
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP Scriptlet tag that prints the user
name
Welcome.jsp
Index.html <html>
<html> <body>
<body> <%
<form action="welcome.jsp"> String name=request.getParameter("
<input type="text" name="uname uname");
"> out.print("welcome "+name);
<input type="submit" value="go" %>
><br/> </form>
</form> </body>
</body> </html>
</html>
JSP expression tag
• The code placed within JSP 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.
Syntax of JSP expression tag
• <%= statement %>
Example of JSP expression tag
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Example of JSP expression tag that prints current
• To display the current time, we havetime
used the getTime() method of Calendar class.
The getTime() is an instance method of Calendar class, so we have called it after
getting the instance of Calendar class by the getInstance() method.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Example of JSP expression tag that prints the user
Index.jsp
nameWelcome.jsp
<html>
<body> <html>
<form action="welcome.jsp"> <body>
<input type="text" name="uname"><br/ <
> <input type="submit" value="go"> %= "Welcome "+request.getParameter("un
ame") %> </body>
</form>
</html>
</body>
</html>
JSP Declaration Tag
• The 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.
EG
index.html
welcome.jsp
<%
<form action="welcome.jsp">
String name=request.getParameter("uname"
<input type="text" name="uname">
); out.print("welcome "+name);
<input type="submit" value="go"><br/
%>
> </form>
JSP response implicit object
• In JSP, response is an 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.
EG
index.html welcome.jsp
<form action="welcome.jsp"> <%
<input type="text" name="uname"> response.sendRedirect("http://
<input type="submit" value="go"><br/> www.google.com");
</form> %>
The out Object:
• The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is
used to send content in a response.
• The initial JspWriter object is instantiated differently depending on whether the
page is buffered or not. Buffering can be easily turned off by using the
buffered='false' attribute of the page directive.
• The JspWriter object contains most of the same methods as the java.io.PrintWriter
class. However, JspWriter has some additional methods designed to deal with
buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.
• Following are the important methods which we would use to write boolean char,
int, double, object, String etc.
….
Method Description
out.println(dataType dt) Print a data type value then terminate the line with new line
character.
• The application object is direct wrapper around the ServletContext object for the
generated Servlet and in reality an instance of a javax.servlet.ServletContext object.
• This object is a representation of the JSP page through its entire lifecycle. This object
is created when the JSP page is initialized and will be removed when the JSP page is
removed by the jspDestroy() method.
• By adding an attribute to application, you can ensure that all JSP files that make up
your web application have access to it.
The config Object:
• The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
• There are 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
1. import
2. contentType
3. extends
4. info
5. buffer
6. language
7. isELIgnored
8. isThreadSafe
9. autoFlush
10. session
11. pageEncoding
12. errorPage
13. isErrorPage
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.
• EG:
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
contentType
• The extends attribute defines the parent class that will be inherited by the
generated servlet.
• It is rarely used.
Exception Handling in JSP
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
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).
• Advantage of Include directive
Code Reusability
• Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive
• In this example, we are including the content of the header.html file. To run this
example you must create an header.html file.
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
JSP Taglib directive
• The JSP taglib directive is used to define a tag library that defines many tags. We use
the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we
will use this tag so it will be better to learn it in custom tag.
• Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Example of JSP Taglib directive
• In this example, we are using our tag named currentDate. To use this tag we must
specify the taglib directive so the container may get information about the tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
JSP Action Tags
• 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 pages and to use Java Bean.
The Jsp action tags
• The jsp:forward action tag is used to forward the request to another resource it may
be jsp, html or another resource.
• Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
• Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" /> </
jsp:forward>
Example of jsp:forward action tag without
parameter
Index.jsp Printdate.jsp
<html> <html>
<body> <body>
<h2>this is index page</h2> <
<jsp:forward page="printdate.jsp" /> % out.print("Today is:"+java.util.Calendar.
</body> getInstance().getTime()); %>
</html> </body>
</html>
Example of jsp:forward action tag with parameter
Index.jsp Printdate.jsp
<html>
<html>
<body>
<body>
<h2>this is index page</h2> <
<jsp:forward page="printdate.jsp" >
% out.print("Today is:"+java.util.Calendar.
<jsp:param name="name" value="java
getInstance().getTime()); %>
tpoint.com" /> <%= request.getParameter("name") %>
</jsp:forward> </body>
</body> </html>
</html>
•
• 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 isbetter 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.
Advantage of jsp:include action tag
• <jsp:include page="relativeURL | <%= expression %>" />
Syntax of jsp:include action tag with parameter
• <jsp:include page="relativeURL | <%= expression %>">
• <jsp:param name="parametername" value="parametervalue |
<%=expression%>" />
• </jsp:include>
Example ofindex.jsp
In this example, jsp:include
file includesaction tag
the content without
of the parameter
printdate.jsp file.
index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
eg
Java Bean
//employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
How to access the java bean class?
• To access the java bean class, we should use getter and setter method.
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
jsp:useBean action tag
<jsp:useBean id= "instanceName" scope= "page | request | session |
application" class= "packageName.className" type= "packageNam
e.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
Attributes and Usage of jsp:useBean action tag
id: is used to identify the bean in the specified scope.
scope: represents the scope of the bean. It may be page, request, session or application. The
default scope is page.
page: specifies that you can use this bean within the JSP page. The default scope is page.
request: specifies that you can use this bean from any JSP page that processes the same request. It
has wider scope than page.
session: specifies that you can use this bean from any JSP page in the same session whether
processes the same request or not. It has wider scope than request.
application: specifies that you can use this bean from any JSP page in the same application. It has
wider scope than session.
class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must
have no-arg or no constructor and must not be abstract.
type: provides the bean a data type if the bean already exists in the scope. It is mainly used with
class or beanName attribute. If you use it without class or beanName, no bean is instantiated.
beanName: instantiates the bean using the java.beans.Beans.instantiate() method.
Simple example of jsp:useBean action tag
• Calculator.java (a simple Bean class)
package com.javatpoint;
public class Calculator{
public int cube(int n){return n*n*n;}
}
Index.jsp
<jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
Jsp:setProperty and jsp:getProperty action tags
• The setProperty and getProperty action tags are used for developing web
application with Java Bean. In web devlopment, bean class is mostly used because it
is a reusable software component that represents data.
• The jsp:setProperty action tag sets a property value or values in a bean using the
setter method.
MVC in JSP
• MVC stands for Model View and Controller. It is a design
pattern that separates the business logic, presentation logic
and data.
• Controller acts as an interface between View and Model.
Controller intercepts all the incoming requests.
• Model represents the state of the application i.e. data. It can
also have business logic.
• View represents the presentaion i.e. UI(User Interface).
Architecture
Implementation
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
Advantage of MVC (Model 2) Architecture
• Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag
and separates the business logic from the JSP page.
• The same business logic can be used many times by the use of custom tag.
Advantages of Custom Tags
• There are two ways to use the custom tag. They are given below:
<prefix:tagname attr1=value1....attrn=valuen />
<prefix:tagname attr1=value1....attrn=valuen >
body code
</prefix:tagname>
JSP Custom Tag API
• The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom
tag API. The JspTag is the root interface in the Custom Tag hierarchy.
JspTag interface
• The JspTag is the root interface for all the interfaces and classes
used in custom tag. It is a marker interface
Tag interface
• The Tag interface is the sub interface of JspTag interface. It provides methods to
perform action at the start and end of the tag.
Fields of Tag interface
public static int EVAL_PAGE it evaluates the JSP page content after
the custom tag.
public static int SKIP_BODY it skips the body content of the tag.
public static int SKIP_PAGE it skips the JSP page content after the
custom tag.
Methods of Tag interface
Method Name Description
public void setPageContext(PageContext pc) it sets the given PageContext object.
public int doStartTag()throws JspException it is invoked by the JSP page implementation object. The JSP
programmer should override this method and define the business
logic to be performed at the start of the tag.
public int doEndTag()throws JspException it is invoked by the JSP page implementation object. The JSP
programmer should override this method and define the business
logic to be performed at the end of the tag.
public void release() it is invoked by the JSP page implementation object to release the
state.
Thank You