Java Server Page
Java Server Page
What is 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.
Advantages of JSP
1) Extension to Servlet
2) Easy to maintain
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of
JSP.
Directory Structure of JSP
The directory structure of JSP page is same as Servlet. We contains the JSP page
outside the WEB-INF folder or in any directory.
Scripting Elements
The scripting element provides the ability to insert java code inside the JSP. There are
three types of scripting elements:
Scriptlet tag
Expression tag
Declaration tag
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
Simple Example of JSP Scriptlet Tag
In this example, we are displaying a welcome message.
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
In this example, we have created two files index.html and welcome.jsp. The index.html
file gets the username from the user and the welcome.jsp file prints the username with
the welcome message.
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. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
JSP Expression Tag
The code placed within 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.
<jsp:expression>
expression
</jsp:expression>
1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5.
6. </html>
Note: Do not end your statement with semicolon in case of expression tag.
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The index.html
file gets the username and sends the request to the welcome.jsp file, which displays the
username.
index.html
1. <html>
2. <body>
3.
4. <form action="welcome.jsp">
5. <input type="text" name="uname"><br/>
6. <input type="submit" value="go">
7. </form>
8. </body>
9. </html>
welcome.jsp
1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </form>
5. </body>
6. </html>
The JSP declaration tag is used to declare fields and methods. The code written inside
the JSP declaration tag is placed outside the service() method of auto generated Servlet.
So it doesn't get memory at each request.
<jsp:declaration>
code fragment
</jsp:declaration>
Difference between the JSP scriptlet tag and JSP
declaration tag ?
JSP Scriptlet Tag JSP Declaration Tag
TheJSP scriptlet tag can only declare The JSP declaration tag can declare variables
variables not methods. as well as methods.
The declaration of scriptlet tag is placed The declaration of JSP declaration tag is
inside the _jspService() method. placed outside the _jspService() method.
In this example of JSP declaration tag, we are declaring the field and printing the value
of the declared field using the JSP expression tag.
index.jsp
1. <html>
2. <body>
3.
4. <%! int data=50; %>
5. <%= "Value of the variable is:"+data %>
6.
7. </body>
8. </html>
In this example of JSP declaration tag, we are defining the method which returns the
cube of given number and calling this method from the JSP expression tag. But we can
also use JSP scriptlet tag to call the declared method.
index.jsp
1. <html>
2. <body>
3.
4. <%!
5. int cube(int n){
6. return n*n*n*;
7. }
8. %>
9.
10. <%= "Cube of 3 is:"+cube(3) %>
11.
12. </body>
13. </html>
There are 9 JSP implicit objects. These objects are created by the web containers that
are available to all the JSP pages. The available implicit objects are out, request, config,
session, application etc.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
web.xml file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6.
7. <init-param>
8. <param-name>dname</param-name>
9. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10. </init-param>
11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name>sonoojaiswal</servlet-name>
16. <url-pattern>/welcome</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. out.print("Welcome "+request.getParameter("uname"));
6.
7. String driver=config.getInitParameter("dname");
8. out.print("driver name is="+driver);
9.
10.
11. %>
12. </body>
13. </html>
pageContext implicit object
page
request
session
application
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. 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_SCO
PE);
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
JSP directives
The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
page directive
include directive
taglib directive
The page directive defines attributes that apply to an entire JSP page.
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".
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.
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) 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:
8) 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.
1. //index.jsp
2. <html>
3. <body>
4.
5. <%@ page errorPage="myerrorpage.jsp" %>
6.
7. <%= 100/0 %>
8.
9. </body>
10. </html>
9) 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>
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).
1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </html>
jsp:forward
jsp:include
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:plugin
jsp:param
jsp:fallback
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean
development. So we will see these tags in bean developement.
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>
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.
code reusability
File: index.jsp
1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:include page="printdate.jsp" />
6.
7. <h2>end section of index page</h2>
8. </body>
9. </html>
File: printdate.jsp
HTML File
<html>
<body>
<form action="main.jsp" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
main.jsp
<%
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
response.addCookie( firstName );
response.addCookie( lastName );
%>
<html>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Reading Cookies with JSP
<html>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}else{
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html>
To delete cookies is very simple. If you want to delete a cookie then you simply need to
follow up following three steps:
Example:
<html>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ){
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " +
cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>
</html>
HttpSession Object
PageCounter Example
<html>
<head>
<title>SELECT Operation</title>
</head>
<body>
</body>
</html>
INSERT Operation
Following example shows how we can execute SQL INSERT statement using JTSL in JSP
programming:
<html>
<head>
<title>JINSERT Operation</title>
</head>
<body>
</body>
</html>
DELETE Operation
Following example shows how we can execute SQL DELETE statement using JTSL in JSP
programming:
<html>
<head>
<title>DELETE Operation</title>
</head>
<body>
</body>
</html>
UPDATE Operation
Following example shows how we can execute SQL UPDATE statement using JTSL in JSP
programming:
<html>
<head>
<title>DELETE Operation</title>
</head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>