JSP by Sekhar Sir
JSP by Sekhar Sir
In a scriptlet tag, method definitions are not allowed. Because at translation time, the method
goes to _jspService() mehthod, but java does not allow one method definition in another method.
For example,
This is invalid
Thursday, August 14, 2014
expression tag:-
An expression tag is used to find the result of an expression and to print that result on browser for
each request.
An expression tag can be writtern in a jsp page in two ways.
<%=
expression
%>
This comes under html syntax
<jsp:expression>
expression
</jsp:expression>
Every expression tag will be first translated to out.print statement and then that statement will be
inserted to _jspService() method. So an expression tag will be executed for each request.
For example,
a.jsp
-----
<%
int a=100, b=200;
%>
<%=
a*b;
%>
a_jsp.java
public class a_jsp extends HttpJspBase
{
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
int a=100;
int b=200;
out.print(a*b);
}
}
expression tag translated code valid/invalid
<%= int x=100; %> out.print(int x=100;); ×
<%= c=a+b %> out.print(c=a+b); ×
<%= a,b %> out.print(a,b); ×
<%= a+b; %> out.print(a+b;); ×
<%= out.print(a) %> out.print(out.print(a)); ×
<%= this.x+this.y %> out.print(this.x+this.y);
<%= for(int i=1; i<=5; i++){}%> out.print(for(int i=1; i<=5; i++) ×
{});
declaration tag:-
This tag is used to create/define global variables or methods in a jsp page.
At translation time, the variables and methods of a declaration taggoes to class, not to service
method.
A declaration tag can be written in 2 ways
<%! declaration %> ---- html syntax
<jsp:declaration> declaration </jsp:declaration> --- xml syntax.
A declaration tag of jsp will be executed for once.
Example1:-
a.jsp
-----
<%!
int a=10;
%>
<%
int b=20;
%>
a_jsp.java
public class a_jsp extends HttpJspBase
{
int a=10; //instance/global variable
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
int b=20; //local variable
}
}
Example 2:
a.jsp
-----
<%!
public String sayHello()
{
return "Hello";
}
%>
<%
String s= sayHello();
out.print(s);
%>
a_jsp.java
-----------
public class a_jsp extends HttpJspBase
{
public String sayHello()
{
return "Hello";
}
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String s = sayHello();
out.print(s);
}
}
Q. Can we write a static method in a declaration tag or not ?
Ans: Yes.
a.jsp
-----
<%!
public static String sayHello()
{
return "Hello";
}
%>
<%
String s= a_jsp.sayHello();
out.print(s);
%>
Q. Can we use implicit object of jsp in a declaration tag?
Ans: No, implicit objects are available only for the code which goes to _jspService() method, but not to
the code goes to the class.
<%!
public void sayHello();
out.println(“Hello”);
%>
This is invalid statement. Because out is an implicit object, not allowed in declaration tag.
<%
out.println(“Hello”);
%>
This is valid.
Friday, August 15, 2014
Q. Which tag of jsp is required to override life cycle init and destroy methods of a jsp?
Ans: declaration tag.
a.jsp
------
<%!
public void jspInit()
{
}
public void jspDestroy()
{
}
%>
Q. Can we override servlet life cycle methods in a jsp page?
Ans:No.Reason is at the time of translating a jsp to servlet, the super class given by server made servlet
life cycle method as final. A super class final method cannot be overridden in sub class.
For example, In Tomcat server, HttpJspBase is the super class of JES and it made servlet life cycle
methods as final. So we cannot override final method in sub class.
Q. Can we write interfaces and classes in a jsp page or not?
Ans: YES. If we write an interface or a class in declaration tag then that code goes to class at translation
time. In java we can write an interface with in a class and a class with in a class. So it is possible.
Comments in JSP:-
In a jsp we can add 3 types of comments.
1. Html Comment.
2. Jsp Comment.
3. Java Comment.
Html and Jsp comments are allowed directly in a page but not allowed in a declaration or a
scriptlet tag.
<!-- Comments --> ----- html comment tag.
<%-- Comments --%> ----- jsp comment
Expression tag of jsp doesn’t allow comments.
Declaration tag and scriptlet tag allows only java comments.
<%
//local variable ----- allowed
int x = 10;
<%-- local variable2 --%> ----- not allowed
int y =20;
<!-- local variable3 --> ----- not allowed
int z = 30;
%>
After translation, in JES html and java comments are visible in _jspService() method. But jsp
comments are invisible. So we call jsp comment as hidden comment.
Html comments come to browser along with response. So we can see html comment on the
browser by opening view source of the page.
Example1:
The following jsp page counts no of request comes from browser
http://localhost:3488/JspApp1/a.jsp
In tomcat server, internal servlet (JES) can be seen at the following location.
C:\Program File\Apache Software Foundation\Catalina\localhost\JspApp1\org\apache\jsp
Q. How a container identifies whether a jsp page is modified or not?
Ans:
A container internally use a file comparison tool that tool tells container whether a jsp page is modified or
not.
For example, Tomcat uses a file comparison tool internally araxis.
Wednesday, August 20, 2014
In the following example, we want to communicate from html to jsp.
Esample: JspApp2--------------------------------------
..
Jsp Directives:-
Directives of jsp are not used for inserting any java code and not used for generating output to the
browser.
Directives are used to give some direction to the container, to be followed at translation time.
In jsp, we have 3 directives:
1. include
2. page
3. taglib
include directive:-
This directive tag tells container that, include source code of one file to another at the translation
time.
We can write this directive tag in html and xml syntax like the following:
<%@ include file="B.jsp" %> ------- html syntax
<jsp:directive.include include file="B.jsp" /> ------- xml syntax
This include directive tag includes source code of a destination file to a source file.After that, if
any changes are done in the destination file, then they are not affected/reflected in the source
file. So this is called compile-time/static including.
We can include the source code of multiple destination files into a single source file.
A destination file can be either html or a jsp page.
page directive:-
This directive is to set an important behavior for a jsp page like session management, error page
handling, buffer etc.
We can write this page directive either in html or in xml syntax.
<%@page attributes%> ------------ html syntax
<jsp:directive.page attributes%> ----------- xml syntax
1. session:
This attribute either enables or disables session management in jsp.
The default value of this attribute is true. It means by default sessions are enabled in jsp.
If we want to disable, session management in jsp then we need to add the page directive like
the following:
<%@page session=”false”%>
If the session management is disabled then it cannot use session object (implicit object
/readymade object) in that page.
2. import:-
This attribute is used for importing a pre-defined or user-defined java package in to a jsp
page.
In a jsp page, a package can be imported at anywhere in the page. It means, either at on top or
at bottom, or at middle of the page.
At translation time, container will collect all import attribute and imports at top of the servlet.
We can import multiple packages by separating with “,” or we can repeat import attribute for
multiple times in a jsp page.
Among multiple attributes of page directive, the only one attribute which is repeatable with
different values is import.
<%@page import="java.util.*"%> ----- valid
<%@page import="java.util.*","java.sql.*"%> ------ valid
<%@page import="java.util.*" import="java.sql.*"%> ------ valid
<%@page import="java.util.*"
import-"java.util.*"%> ------ valid
<%@page import="java.util.*"%>
-----------------------------
-----------------------------
<%@page import="java.sql.*"%> ----- valid
3. language:-
This attribute is used for setting language to be used in the scripting elements.
The default value and the only available value is java.
<%@page language="java"%>
4. isThreadSafe:-
This attribute tells a container whether multiple threads are allowed concurrently or a single
thread is allowed concurrently to access a jsp page.
The default value of isThreadSafe is “true”. It means multiple threads are allowed
concurrently to access a page.
If we write isThreadSafe=”false”, then one thread allowed at a time to access a jsp page.
If we write isThreaSave=”false”, then at the time of translation, a container implements
internal servlet class (JES) from SingleThreadModel interface.
Thursday, August 21, 2014
5. errorPage:-
This attribute is to tell the container that, send the control to another page, if an exception is
occurred in the current page at the runtime.
If only exception occurs then the control will be transferred otherwise not transferred.
For example,
a.jsp
----------------
<%@page errorPage="error.jsp"%>
6. isErrorPage:-
The default value of isErrorPage attribute is “false”.
By default, a jsp page does not act as an error page. Because by default isErrorPage = “false”.
If we want to make a jsp page as an error page, then we should set isErrorPage = “true”.
If a jsp page is acting as error page, then exception object is allowed to use in that page.
For example,
error.jsp
-----------
<%@page isErrorPage="true"%>
7. contentType:-
This attribute is to set MIME type of the response.
The default value of this attribute is “text/html”.
In a jsp page, contentType can be set in 2 ways.
(a) Using contentType attribute.
(b) By calling setContentType() method.
<%@page contentType="text/xml"%>
<%
response.setContentType("text/xml")
%>
8. buffer:-
In jsp, we use an implicit object is called “out”, for sending response to the browser.
out is an implicit object of class JspWriter.
By default, out object maintains a buffer (cache) and the statements are stored in that buffer
first. Later from buffer the data will be transferred to the response object.
In servlet, we use PrintWriter class object and it directly writes the response data into
response object.
The advantage the buffer in the middle, it reduces the no. of inter actions with the response
object. So it improves performance.
If you want to increase or reduce or remove a buffer then we use buffer attribute.
The default value of buffer attribute is 8kb.
If buffer is removed, then PrintWriter and JspWriter classes, both becomes equal.
<%@page buffer="15KB"%>
<%%page buffer="none"%>
9. autoFlush:-
This attribute is used to either enable or disable flush mode in jsp.
The default value of this attribute is “true”. It means autoFlush mode is enabled.
When autoFlush mode is enabled then a container will automaticlay flush a buffer, when it is full
or when it is close.
Flushing a buffer means, transferring the data to the response object and clearing it from the
buffer.
If autoFlush mode is disabled, then a programmer has to call flush() method explicitly to flush the
buffer.
If a programmer calls flush() method after a buffer is full then BufferOverFlow exception will be
thrown.
10. Info:-
This attribute is used for writing a page level readable comment.
If this attribute is added in jsp page, then at translation time, a container will created
gerServletInfo() method in JES.
We can read the message of info attribute by calling getServletInfo() under scriptlet tag of jsp.
a.jsp
---------------
<%@page info="A sa,ple message"%>
<%
String str=getServletInfo();
%>
11. extends:-
This attribute tells a container to extend the internal servlet from a given class.
If we want to set our class name as a super class for the internal JES then first we need to create
our class by extending HttpServlet and by implementing HttpJspPage interface.
<%@page extends=”com.satya.servlet.MyServlet”%>
public class MyServlet extends HttpServlet implements HttpJspPage
{}
Attribute Default value
session true
Import -
Language java
isThreadSafe true
errorPage -
isErrorPage none
contentType text/html
Buffer 8kb
autoFlust true
Info -
Extends -
Friday, August 22, 2014
Standard actions in JSP:-
The actions tags of jsp are used for communicating a jsp with another jsp or a servlet or an applet
or a java bean.
The action tag of jsp follows only xml syntax.
We have 9 action tags in jsp.
1. <jsp:forward>
2. <jsp:incllude>
3. <jsp:param>
4. <jsp:params>
5. <jsp:plugin>
6. <jsp:fallback>
7. <jsp:useBean>
8. <jsp:setProperty>
9. <jsp:getProperty>
<jsp:forward>:-
This action tag is used for forwarding a request from a jsp to another jsp or a servlet or a html.
Generally, if a huge logic is required in a jsp then we divide that logic into multiple jsp pages and
then we apply forwarding technique.
If destination is a jsp or html then file name is required and if destination is a servletthen url
pattern is requied.
<jsp:forward page="/srv1"/>
<jsp:forward page="b.jsp"/>
<jsp:forward page="index.html"/>
When a request is forwarded then along-with the request, automatically request parameters send
from browser or also forwarded. If you want to attach additional parameters then we use
<jsp:param>tag inside <jsp:forward> tag.
<jsp:forward page="b.jsp">
<jsp:param name="p1" value="10"/>
<jsp:param name="p2" value="20"/>
</jsp:forward>
In the following example, we are using jsp to servlet application by forwarding a request.
ForwardTest
WEB-INF
web.xml
classes
SalaryServlet.java
index.html
Program:----------------
<jsp:include>
This action tag is used for including the response of one resource like a jsp or a servlet or a html
into another jsp page.
In jsp, we have two types of including,
1. include directive
2. include action
include directive is for static including and include action is for dynamic including.
Internally a container uses RequestDispatcher’s include method, for executing <jsp:include>tag.
************ We choose include directive when a destination is a static page like html and we
choose include action, when a destination is a dynamic resource like a jsp or a servlet.
Saturday, August 23, 2014
<jsp:plugin>
This action tag is given for integrating a jsp page with an applet.
When a jsp wants to display response in a graphics format in a browser, then a jsp page will
integrates with an applet.
In applet class, we have a method called paint(). In this method we can create output in graphical
format using methods of Graphics class.
<jsp:plugin type="applet" code="classsname" width="200" height="200">
<jsp:params>
<jsp:param ----------/>
<jsp:param------------/>
</jsp:params>
<jsp:fallback>Alternate Message</jsp:fallback>
</jsp:plugin>
<jsp:useBean>
This standard action tag is to establish a connection between a jsp page and a java bean.
In web applications of java, jsp and java bean communication is required in the following two
cases:
1. In a real-time MVC project, a model class (business class) will set the data to a java bean
and a jsp (view) will read the data from a bean and finally displays it on the browser. In
this class jsp to a java bean communication is required.
2. If multiple jsp pages need common java logic then it separates that java code into a bean
and then we call the bean from jsp. In this case also jsp to java bean communication is
required.
<jsp:useBean> tag is used for creating an object of a bean class in a jsp page.
<jsp:useBean id ="object name" class="fully qualified class"
scope="page/request/session/application"/>
Monday, August 25, 2014
Every java class is not a java bean automatically. A class should have the following qualities
to make it as a java bean.
1. Class must be public
2. Class must contain default constructor
3. Each private property of the class must have setter or getter or both methods.
4. A class can at most implement Serializable interface.
<jsp:setProperty>:
This action tag is to set an input value to set input value to a property on a variable of bean
class by calling setter () method of the property.
When a request comes from browser, the protocol is http and it is unknown for the java bean.
So, directly input values from browser can’t be send to a java bean.
The flow of setting input values is, a jsp page takes request from browser and it will set input
values to bean using <jsp:setProperty> tag.
<jsp:setProperty> must be used inside <jsp:useBean> tag.
<jsp:setProperty> property contains four attributes
1. Name Object name:
The values of this attribute must be same as the value of id of the bean class
2. Property variable name in bean class
3. Param request parameter name
4. Value static value
Name and property attributes are mandatory. We shouldn’t use param and value attribute at
time.
If request parameters names and variable name of java beans or matched then we can directly
write <protperty=”*”> .
1. Name, property,value allowed
2. Name ,property, param allowed
3. Property, param not allowed
4. Name, property,name, param not allowed.
<jsp:getProperty> tag:
This action tag is used to read the value of a variable of bean class by calling its getter ()
method.
This action tag must be written at outside of <jsp:useBean> tag.
This action tag has only two attribute called name and property.
In this tag property=”*” is not allowed.
In the following we are verifying username and password using jsp to bean communication.
Login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login page</title>
</head>
<body>
<form action="login.jsp">
<table align="center">
<tr><td>username</td><td><input type="text" name="uname"></td></tr>
<tr><td>Password</td><td><input type="password" name="pwd"></td></tr>
<tr><td> </td><td><input type="submit" value="SUBMIT"></td></tr>
</table>
</form>
</body>
</html>
Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login JSP</title>
</head>
<body>
<!-- login.jsp -->
<jsp:useBean id="loginBean" class="com.sunil.bean.LoginBean">
<jsp:setProperty name="loginBean" property="*"/>
</jsp:useBean>
<%
String result=loginBean.check();
%>
Username: <jsp:getProperty name="loginBean" property="uname"/>
<br>
Password: <jsp:getProperty name="loginBean" property="pwd"/>
<br>
<%= result %>
</body>
</html>
//LoginBean.java
package com.sunil.bean;