JSP Class Notes
JSP Class Notes
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 Tags, etc.
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the 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.
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.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code. Moreover,
we can use EL, implicit objects, etc.
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, 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.
To create the first JSP page, write some HTML code as given below, and save it by .jsp extension. We have
saved this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in apache
tomcat to run the JSP page.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the JSP page.
We will learn scriptlet tag later.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
No, there is no need of directory structure if you don't have class files or TLD files. For example, put JSP
files in a folder directly and deploy that folder. It will be running fine. However, if you are using Bean class,
Servlet or TLD file, the directory structure is required.
The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB-INF
folder or in any directory.
The JSP API
The JSP API consists of two packages:
1. javax.servlet.jsp
2. javax.servlet.jsp.tagext
javax.servlet.jsp package
The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as follows:
1. JspPage
2. HttpJspPage
o JspWriter
o PageContext
o JspFactory
o JspEngineInfo
o JspException
o JspError
Skip Ad
Methods of JspPage interface
1. public void jspInit(): It is invoked only once during the life cycle of the JSP when JSP page is
requested firstly. It is used to perform initialization. It is same as the init() method of Servlet
interface.
2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP before the JSP
page is destroyed. It can be used to perform some clean up operation.
1. public void _jspService(): It is invoked each time when request for the JSP page comes to the
container. It is used to process the request. The underscore _ signifies that you cannot override
this method.
o scriptlet tag
o expression tag
o declaration tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
HTML Tutorial
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
File: index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>
Note: Do not end your statement with semicolon in case of expression tag.
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
File: index.jsp
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>
The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.
The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as well
not methods. as methods.
The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed
the _jspService() method. outside the _jspService() method.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>
It can also be used to set, get and remove attributes from the jsp request scope.
Let's see the simple example of request implicit object where we are printing the name of the user with
welcome message.
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. String name=request.getParameter("uname");
3. out.print("welcome "+name);
4. %>
Output
Let's see the example of response implicit object where we are redirecting the response to the Google.
Output
Output
5) JSP application implicit object
In JSP, application is an implicit object of type ServletContext.
The instance of ServletContext is created only once by the web container when application or project is
deployed on the server.
This object can be used to get initialization parameter from configuaration file (web.xml). It can also be
used to get, set or remove attribute from the application scope.
Output
6) session implicit object
In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to set,get
or remove attribute or to get session information.
index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
Output
7) pageContext implicit object
In JSP, pageContext is an implicit object of type PageContext class.The pageContext object can be used
to set,get or remove attribute from one of the following scopes:
o page
o request
o session
o application
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
Output
8) page implicit object:
In JSP, page is an implicit object of type Object class.This object is assigned to the reference of auto
generated servlet class. It is written as:
Object page=this;
For using this object it must be cast to Servlet type.For example:
<% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use this object directly in jsp.For example:
<% this.log("message"); %>
error.jsp
JSP directives
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
o page directive
o include directive
o taglib directive
o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage
1)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.
1. <html>
2. <body>
3.
4. <%@ page import="java.util.Date" %>
5. Today is: <%= new Date() %>
6.
7. </body>
8. </html>
2)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".
Skip Ad
1. <html>
2. <body>
3.
4. <%@ page contentType=application/msword %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>
3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely
used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo()
method of Servlet interface.
1. <html>
2. <body>
3.
4. <%@ page info="composed by Sonoo Jaiswal" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>
The web container will create a method getServletInfo() in the resulting servlet.For example:
5)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.
Example of buffer attribute
1. <html>
2. <body>
3.
4. <%@ page buffer="16kb" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>
6)language
The language attribute specifies the scripting language used in the JSP page. The default value is "java".
7)isELIgnored
We can 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.
1. <%@ page isELIgnored="true" %>//Now EL will be ignored
8)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 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:
The web container in such a case, will generate the servlet as:
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.
1. //index.jsp
2. <html>
3. <body>
4.
5. <%@ page errorPage="myerrorpage.jsp" %>
6.
7. <%= 100/0 %>
8.
9. </body>
10. </html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.
1. //myerrorpage.jsp
2. <html>
3. <body>
4.
5. <%@ page isErrorPage="true" %>
6.
7. Sorry an exception occured!<br/>
8. The exception is: <%= exception %>
9.
10. </body>
11. </html>
Code Reusability
1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </html>
Note: The include directive includes the original content, so the actual page size grows at runtime.
1. <html>
2. <body>
3.
4. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
5.
6. <mytag:currentDate/>
7.
8. </body>
9. </html>
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
error.jsp
Keep Watching
Competitive questions on Structures in Hindi
00:00/03:34
Competitive questions on Structures in Hindi
Keep Watching
Competitive questions on Structures in Hindi
Keep Watching
Competitive questions on Structures in Hindi
Keep Watching
Keep Watching
Competitive questions on Structures in Hindi
00:00/03:34
Competitive questions on Structures in Hindi
Keep Watching
Nested Structure in C
Keep Watching
1. <web-app>
2.
3. <error-page>
4. <exception-type>java.lang.Exception</exception-type>
5. <location>/error.jsp</location>
6. </error-page>
7.
8. </web-app>
This approach is better if you want to handle any exception. If you know any specific error code and you
want to handle that exception, specify the error-code element instead of exception-type as given below:
1) web.xml file if you want to handle the exception for a specific error code
1. <web-app>
2.
3. <error-page>
4. <error-code>500</error-code>
5. <location>/error.jsp</location>
6. </error-page>
7.
8. </web-app>
3) process.jsp
Now, you don't need to specify the errorPage attribute of page directive in the jsp page.
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. %>
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are
given below.
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.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development. So we will see
these tags in bean developement.
index.jsp
1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:forward page="printdate.jsp" />
6. </body>
7. </html>
printdate.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
index.jsp
1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:forward page="printdate.jsp" >
6. <jsp:param name="name" value="hello" />
7. </jsp:forward>
8.
9. </body>
10. </html>
printdate.jsp
1. <html>
2. <body>
3.
4. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
5. <%= request.getParameter("name") %>
6.
7. </body>
8. </html>
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are
given below.
JSP Action Tags Description
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.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development. So we will see
these tags in bean developement.
index.jsp
1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:forward page="printdate.jsp" />
6. </body>
7. </html>
printdate.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
index.jsp
1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:forward page="printdate.jsp" >
6. <jsp:param name="name" value="javatpoint.com" />
7. </jsp:forward>
8.
9. </body>
10. </html>
printdate.jsp
1. <html>
2. <body>
3.
4. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
5. <%= request.getParameter("name") %>
6.
7. </body>
8. </html>
There are many implicit objects, operators and reserve words in EL.
1. ${ expression }
pageScope it maps the given attribute name with the value set in the page scope
requestScope it maps the given attribute name with the value set in the request scope
sessionScope it maps the given attribute name with the value set in the session scope
applicationScope it maps the given attribute name with the value set in the application scope
EL param example
In this example, we have created two files index.jsp and process.jsp. The index.jsp file gets input from the
user and sends the request to the process.jsp which in turn prints the name of the user using EL.
index.jsp
1. <form action="process.jsp">
2. Enter Name:<input type="text" name="name" /><br/><br/>
3. <input type="submit" value="go"/>
4. </form>
process.jsp
1. Welcome, ${ param.name }
EL sessionScope example
In this example, we printing the data stored in the session scope using EL. For this purpose, we have used
sessionScope object.
index.jsp
1. <h1>First JSP</h1>
2. <%
3. Cookie ck=new Cookie("name","abhishek");
4. response.addCookie(ck);
5. %>
6. <a href="process.jsp">click</a>
process.jsp
1. Hello, ${cookie.name.value}
Precedence of Operators in EL
There are many operators that have been provided in the Expression Language. Their precedence are as
follows:
[] .
()
* / div % mod
+ - (binary)
== != eq ne
&& and
|| or
?:
Reserve words in EL
There are many reserve words in the Expression Language. They are as follows:
lt le gt ge
eq ne true false
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.
first.
File: index.jsp
1. package com.javatpoint;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.RequestDispatcher;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. public class ControllerServlet extends HttpServlet {
10. protected void doPost(HttpServletRequest request, HttpServletResponse response)
11. throws ServletException, IOException {
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14.
15. String name=request.getParameter("name");
16. String password=request.getParameter("password");
17.
18. LoginBean bean=new LoginBean();
19. bean.setName(name);
20. bean.setPassword(password);
21. request.setAttribute("bean",bean);
22.
23. boolean status=bean.validate();
24.
25. if(status){
26. RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");
27. rd.forward(request, response);
28. }
29. else{
30. RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
31. rd.forward(request, response);
32. }
33.
34. }
35.
36. @Override
37. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
38. throws ServletException, IOException {
39. doPost(req, resp);
40. }
41. }
File: LoginBean.java
1. package com.javatpoint;
2. public class LoginBean {
3. private String name,password;
4.
5. public String getName() {
6. return name;
7. }
8. public void setName(String name) {
9. this.name = name;
10. }
11. public String getPassword() {
12. return password;
13. }
14. public void setPassword(String password) {
15. this.password = password;
16. }
17. public boolean validate(){
18. if(password.equals("admin")){
19. return true;
20. }
21. else{
22. return false;
23. }
24. }
25. }
File: login-success.jsp
1. <%@page import="com.javatpoint.LoginBean"%>
2.
3. <p>You are successfully logged in!</p>
4. <%
5. LoginBean bean=(LoginBean)request.getAttribute("bean");
6. out.print("Welcome, "+bean.getName());
7. %>
File: login-error.jsp
Output
JSTL (JSP Standard Tag Library)
The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
Advantage of JSTL
1. Fast Development JSTL provides many tags that simplify the JSP.
2. Code Reusability We can use the JSTL tags on various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.
JSTL Tags
There JSTL mainly provides five types of tags:
Core tags The JSTL core tag provide variable support, URL management, flow control, etc. The URL
for the core tag is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c.
Function The functions tags provide support for string manipulation and string length. The URL
tags for the functions tags is http://java.sun.com/jsp/jstl/functions and prefix is fn.
Formatting The Formatting tags provide support for message formatting, number and date
tags formatting, etc. The URL for the Formatting tags
is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.
XML tags The XML tags provide flow control, transformation, etc. The URL for the XML tags
is http://java.sun.com/jsp/jstl/xml and prefix is x.
SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.
The same business logic can be used many times by the use of custom tag.
1. Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet tag which
is considered bad programming approach in JSP.
2. Separation of business logic from JSP The custom tags separate the the business logic from the
JSP page so that it may be easy to maintain.
3. Re-usability The custom tags makes the possibility to reuse the same business logic again and
again.
Syntax to use custom tag
There are two ways to use the custom tag. They are given below:
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.
There are four fields defined in the Tag interface. They are:
Field Name Description
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.
public int doStartTag()throws it is invoked by the JSP page implementation object. The JSP
JspException programmer should override this method and define the
business logic to be performed at the start of the tag.
public int doEndTag()throws it is invoked by the JSP page implementation object. The JSP
JspException 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.
IterationTag interface
The IterationTag interface is the sub interface of the Tag interface. It provides an additional method to
reevaluate the body.
TagSupport class
The TagSupport class implements the IterationTag interface. It acts as the base class for new Tag
Handlers. It provides some additional methods also.
Pagination in JSP
We can create pagination example in JSP easily. It is required if you have to display many records.
Displaying many records in a single page may take time, so it is better to break the page into parts. To do
so, we create pagination application.
We have created "emp" table in "test" database. The emp table has three fields: id, name and salary. Either
create table and insert records manually or import our sql file.
index.jsp
view.jsp
Emp.java
1. package com.javatpoint.beans;
2.
3. public class Emp {
4. private int id;
5. private String name;
6. private float salary;
7. //getters and setters
8. }
EmpDao.java
1. package com.javatpoint.dao;
2. import com.javatpoint.beans.*;
3. import java.sql.*;
4. import java.util.ArrayList;
5. import java.util.List;
6. public class EmpDao {
7.
8. public static Connection getConnection(){
9. Connection con=null;
10. try{
11. Class.forName("com.mysql.jdbc.Driver");
12. con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","","");
13. }catch(Exception e){System.out.println(e);}
14. return con;
15. }
16.
17. public static List<Emp> getRecords(int start,int total){
18. List<Emp> list=new ArrayList<Emp>();
19. try{
20. Connection con=getConnection();
21. PreparedStatement ps=con.prepareStatement(
22. "select * from emp limit "+(start-1)+","+total);
23. ResultSet rs=ps.executeQuery();
24. while(rs.next()){
25. Emp e=new Emp();
26. e.setId(rs.getInt(1));
27. e.setName(rs.getString(2));
28. e.setSalary(rs.getFloat(3));
29. list.add(e);
30. }
31. con.close();
32. }catch(Exception e){System.out.println(e);}
33. return list;
34. }
35. }
Output