This document contains slides from a lecture on software technologies and JSP. It discusses the responsibilities of servlets and why JSP is better suited for presentation logic. Key points about JSP include that it allows embedding Java code within HTML tags, gets converted to a servlet, and is easier for web designers to use than plain servlets. The document covers scripting elements like scriptlets, declarations, and expressions in JSP as well as directives, implicit objects, and how to retrieve and display data from databases using JSP.
2. CS3002
Lecture 1 / Slide 2
Responsibilities of Servlets
Coding the presentation logic and business logic
together is not a good practice
A change in any one of these requires the modification of the
entire code
Programmers with different skill sets are required for
creating and maintaining these
Servlets, being Java programs, are best suited for
coding business logic
3. CS3002
Lecture 1 / Slide 3
Responsibilities of Servlets
Servlets are not suitable to code presentation logic
It is not easy to mix static contents with dynamic contents in
Servlets
As Servlets are not as easy as HTML, it will be difficult for
web designers to use this technology
A technology with the power of Servlets and ease of
HTML is required to code presentation logic, so that
web designers can also easily use it
4. CS3002
Lecture 1 / Slide 4
JSP
JSP or JavaServer Pages is a technology developed by
Sun Microsystems for coding the presentation layer of
an enterprise application
A JSP file is very similar to an HTML file
Unlike HTML files, JSP files will contain some Java
code also with in <% %> tags
Ex: LongMessageJSP
5. CS3002
Lecture 1 / Slide 5
JSP
When a client requests for a JSP, the Server (For
example, Tomcat), sends the HTML tags as such to the
browser
The code between <% and %> will be compiled,
executed and the output will be send to the browser
JSP
Can be used to code presentation logic
Can be used to generate dynamic pages
Is as simple as HTML, even web designers can use it easily
6. CS3002
Lecture 1 / Slide 6
Servlets Vs JSP
Servlet
Bits of HTML embedded in Java code
Suitable for coding the business layer of an enterprise
application
Created and maintained by Java programmers
JSP
Bits of Java code embedded in HTML
Suitable for coding the presentation layer of an enterprise
application
Created and maintained by web designers
7. CS3002
Lecture 1 / Slide 7
JSP
Internally, the JSP is getting converted to a Servlet
When a user requests for a .jsp file for the first time, the
JSP Container will create a Servlet that would produce
the output that the .jsp file is supposed to produce
The Servlet is compiled, run and the output is given to
the browser
Starting from the second request, there is no overhead
of compilation
IS
CLIEN Request JSP VALID No
T ?
Text COMPILE
Response SERVLET Yes
Class
9. CS3002
Lecture 1 / Slide 9
Implicit Objects some implicit objects
A JSP developer can use
Some of the important objects and their classes are as follows
out - JSPWriter
request - HttpServletRequest
response- HttpServletResponse
session - HttpSession
application - ServletContext
config - ServletConfig
exception - Throwable / JspException
pageContext- PageContext
page - Object
These objects will be declared by the generated Servlet and
hence the statements we write in JSP using these variables will
get a meaning once they are pasted in the Servlet code
10. CS3002
Lecture 1 / Slide 10
Directives //no output to client
page
include
taglib
Scripting elements
Scriptlet
Declaration
expression
Standard actions
forward
include
useBean
11. CS3002
Lecture 1 / Slide 11
Implicit Objects - Example
This example uses the out, request and session objects
Ex: SessionTestJSPForm.html
SessionTestJSP
ReadSessionTestJSP
13. CS3002
Lecture 1 / Slide 13
Tags in JSP
Tags in JSP can be categorized as
Comments
Scripting elements
Directive elements
Action elements
Template data
– Any thing other than the above mentioned four categories
fall under template data
– This will include all HTML tags and text
14. CS3002
Lecture 1 / Slide 14
Comments
Just like any other HTML tag, standard HTML
comment tag also can be used in JSP
<!--
<!-- This is a comment in HTML -->
-->
This comment tag will reach the browser
A JSP specific comment tag is written as follows
<%--
<%-- This is a JSP Comment --%>
--%>
This comment tag will not reach the browser
15. CS3002
Lecture 1 / Slide 15
Character quoting conventions
To get “<%” character in text (static HTML) <%
To get “%>” character in scripting elements %>
To get a single quote in an attribute '
To get a double quote in an attribute "
16. CS3002
Lecture 1 / Slide 16
Scripting tags
SCRIPTING TAGS are three types
SCRIPTLET TAGS
EXPRESSION TAGS
DECLARATION TAGS
17. CS3002
Lecture 1 / Slide 17
Scripting Elements
Scripting elements are elements in the page that include
the Java code
JSP can contain 3 types of scripting elements
Scriptlets <% %>
Declarations <%! %>
Expressions <%= %>
18. CS3002
Lecture 1 / Slide 18
Scripting Elements - Scriptlets
The Java statements that appear between <% and %>
are called scriptlets
This code goes to _jspService() method of servlet
Java statements end in semicolon
Ex: TestJSP
19. CS3002
Lecture 1 / Slide 19
Scripting Elements - Declaration of variables
Variables declared within <% and %> will be local to
the service method of the generated Servlet and each
request will have a separate copy of this variable
<%
int data;
%>
Declarative tag
Variables declared within <%! and %> will be a data
member of the generated Servlet class and all the requests
will use the same copy of this variable
<%!
double amount;
%>
20. CS3002
Lecture 1 / Slide 20
Scripting Elements - Declaration of methods
Methods also can be declared using scripting elements
All variables and methods should be declared within
<%! and %> and they become a method of the
generated Servlet
Ex: MethodTestJSPForm.html
MethodTestJSP
21. CS3002
Lecture 1 / Slide 21
Declaration tag
<html><body>
<%!
int addNum(int n, int m) {
return n + m;
}
int subtractNum(int N1, int N2) {
return N1 - N2;
}
%>
<% out.println("6 + 2 = " + addNum(6, 2)); %>
<% out.println("8 - 5 = " + subtractNum(8, 5) + "<BR>");
</body></html>
22. CS3002
Lecture 1 / Slide 22
Handling form in jsp
<html> <head><title>Using Post Method in JSP Form.</title></head> <body> <form
method="post"> <table border="0" cellpadding="0" cellspacing="0"> <tr>
<td>Enter your name: </td>
<td><input type="text" size="20" name="txtName" /></td> </tr>
<tr> <td> </td> <td><input type="submit" name="B1" value="Submit" />
<input type="reset" name="B2" value= "Reset" /></td> </tr>
</table> </form>
<% if(request.getParameter("txtName") != null)
{
if(request.getParameter("txtName"). equals(""))
out.println("<html><font color=red>Please enter your name.</font></html>");
else
out.println("Your username is: " + request.getParameter("txtName"));
} %>
</body> </html>
25. CS3002
Lecture 1 / Slide 25
Scripting Elements - Declaration of JSP Lifecycle methods
The code that should be executed only once when the
JSP is invoked for the first time can be coded in a
method jspInit()
The jspInit() method will be executed only once per JSP,
not per request
Typically this method contains code for initialization
The code that should be executed only once when the
JSP is unloaded from the memory can be coded in a
method jspDestroy()
Typically this method contains code to cleanup the
resources used by the JSP
27. CS3002
Lecture 1 / Slide 27
Scripting Elements - Expressions
The value of an expression can be printed to the
browser using the syntax <%=expression%>
<%
String name = “Software”;
%>
Hello <%=name%>
These expressions doesn’t end with semi-colon. These
are passed as argument to out.print()
28. CS3002
Lecture 1 / Slide 28
Access all the fields from table through JSP
<%
String QueryString = "SELECT * from stu_info";
rs = statement.executeQuery(QueryString);
%>
<TABLE cellpadding="15" border="1" style="background-
color: #ffffcc;"> <% while (rs.next()) { %> <TR>
<TD> <%=rs.getInt(1)%> </TD>
<TD><%=rs.getString(2)%> </TD>
<TD> <%=rs.getString(3)%> </TD>
<TD> <%=rs.getString(4)%> </TD> </TR>
<% } %>
29. CS3002
Lecture 1 / Slide 29
Servlet and JSP
String sql = "select * from message";
Statement s = connection.createStatement();
s.executeQuery (sql);
rs = s.getResultSet();
while (rs.next ()){
//Add records into data list
dataList.add(rs.getInt("id"));
dataList.add(rs.getString("message")); }…..
request.setAttribute("data",dataList);
RequestDispatcher dispatcher = request.getRequestDispatcher(DataPage.jsp);
if (dispatcher != null){ dispatcher.forward(request, response); }
DataPage.Jsp
<body> <table border="1" width="303">
<tr><td width="119"><b>ID</b></td><td width="168"><b>Message</b></td></tr>
<%Iterator itr;%>
<% List data= (List)request.getAttribute("data");
for (itr=data.iterator(); itr.hasNext(); ) {
%>
<tr><td width="119"><%=itr.next()%></td><td width="168"><%=itr.next()%></td></tr>
<%}%> </table></body>
30. CS3002
Lecture 1 / Slide 30
Authentication
<%@ page import="java.sql.*" %>
<% String sql = "select user,password from User";
Statement s = connection.createStatement();
s.executeQuery (sql);
rs = s.getResultSet();
while (rs.next ()){
userName=rs.getString("user");
passwrd=rs.getString("password");
} %>
<%
if(userName.equals(request.getParameter("user")) &&
passwrd.equals(request.getParameter("pass"))){
out.println("User Authenticated");
}
else{
out.println("You are not an authentic person");
} %>
31. CS3002
Lecture 1 / Slide 31
image
<%
psmnt = connection.prepareStatement("SELECT image FROM save_image WHERE id
= ?");
psmnt.setString(1, "11"); // here integer number '11' is image id from the table
rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
} } %>
save_image table
CREATE TABLE save_image ( id int(5) NOT NULL auto_increment, name
varchar(25) default NULL, city varchar(20) default NULL, image blob, Phone
varchar(15) default NULL, PRIMARY KEY (`id`) );
32. CS3002
Lecture 1 / Slide 32
Retrieving data from a file
<%@ page import="java.io.*"%>
<html><body>
<%
String fName = "c:csvmyfile.csv";
String thisLine; int count=0; int i=0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis); %>
<table>
<% while ((thisLine = myInput.readLine()) != null)
{
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++) {
if(i!=0) {
out.print(" " +strar[j]+ " ");
} else { out.print(" <b>" +strar[j]+ "</b> "); }
} out.println("<br>"); i++;
} %> </table> </body> </html>
33. CS3002
Lecture 1 / Slide 33
Export data to a file from database
http://www.roseindia.net/jsp/jdbccsv.shtml
Downloading a file from database
http://www.roseindia.net/jsp/downloadcsv.shtml
35. CS3002
Lecture 1 / Slide 35
Retrieving data posted to a jsp file
from html file
<input type=“text” name=“username” size=“20”>
<html><body>
<%=request.getParameter(“username”) %>
</body></html>
36. CS3002
Lecture 1 / Slide 36
Directive tags
DIRECTIVE TAGS are three types
PAGE DIRECTIVE
INCLUDE DIRECTIVE
TAGLIB DIRECTIVE
37. CS3002
Lecture 1 / Slide 37
Directive Elements
Directive elements provide information to the JSP
container about the page
JSP can contain three types of directives
page
include
taglib
Syntax
<%@ directive attribute="value" %>
<%@ directive attribute1="value1“ attribute2="value2“
...attributeN="valueN" %>
38. CS3002
Lecture 1 / Slide 38
The page Directive
The page directive has the following form
<%@ page attributes %>
Some of the important attributes are
import
session
contentType
errorPage
isErrorPage
isThreadSafe, isELIgnored, language, extends,
session, buffer, autoFlush, info, pageEncoding
39. CS3002
Lecture 1 / Slide 39
The page Directive - import
The import attribute
– Example
<%@ page import = “java.io.*,java.net.Socket” %>
– Just like a normal Java program, the Java code
embedded in a JSP page should import all the classes
and interfaces used in the code
– Note:- Directive elements doesn’t end with semi-colon!!
40. CS3002
Lecture 1 / Slide 40
The page Directive - session
The session attribute
Example
<%@ page session = “false” %>
By default, the generated Servlet creates a HttpSession object
called session
Setting session = “false” prevents the creation of this object
The implicit object, session, is available only if this value is not set to
false
The value of this attribute can be set to false if the Servlet is not
tracking the session
41. CS3002
Lecture 1 / Slide 41
The page Directive - contentType
The contentType attribute
Example
<%@ page contentType = “text/plain” %>
The contentType of the response can be set using
the appropriate MIME type
The default value is “text/html”
42. CS3002
Lecture 1 / Slide 42
The page Directive - errorPage
The errorPage attribute
Example
<%@ page errorPage = “Error.jsp” %>
– In case of any error, the user will be forwarded to Error.jsp.
Error.jsp has the attribute isErrorPage set to true.
– The exception object will be set as an attribute in the request
object so that the Error.jsp can also access the exception
object
43. CS3002
Lecture 1 / Slide 43
The page Directive - isErrorPage
The isErrorPage attribute
– Example
<%@ page isErrorPage = “true” %>
Error pages like Error.jsp in the previous example should contain this
tag
The presence of this tag creates a new Throwable object called
exception in the generated Servlet
The exception generated in the original page and passed as an
attribute of the request will be assigned to this
So, exception is an implicit object that we can use only in error pages
44. CS3002
Lecture 1 / Slide 44
The page Directive - errorPage and isErrorPage
Ex: ErrorTestPageJSP
ErrorPageJSP
45. CS3002
Lecture 1 / Slide 45
The include Directive
The include directive can be used to include the
contents of some other file in a JSP
Example
<%@ include file = "../Header.html" %>
The contents of the included file will be pasted as a part of
the JSP
The contents can be static (HTML Page) or dynamic
(Another JSP)
The contents of a page can thus be separated into more
manageable elements
46. CS3002
Lecture 1 / Slide 46
The include Directive
Many dynamic pages contain common static parts in
them, mostly header and footer
The common static parts can be stored as HTML files
that can be included in a JSP
Ex: IncludeTestJSP
IncludeMeJSP
Header.html
Footer.html
47. CS3002
Lecture 1 / Slide 47
The taglib Directive
The taglib directive will be discussed later in the topic Custom
Actions
Example:
<%@ taglib prefix="blx" uri=“/blx.tld" %>
The "uri" specifies where to find the tag library
description. The "prefix" is unique for the tag library. This
directive is shows that we are using the tags in this library by
starting them with blx:
48. CS3002
Lecture 1 / Slide 48
Action tags
ACTION TAGS are three types
FORWARD ACTION
INCLUDE ACTION
USEBEAN ACTION
49. CS3002
Lecture 1 / Slide 49
Action Elements
Action elements are tags that affect the runtime
behavior of a JSP
Action elements are also known as Standard Actions
Some common standard actions are
<jsp:forward>
<jsp:include>
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
<jsp:param>
50. CS3002
Lecture 1 / Slide 50
Standard Actions - jsp:forward
The <jsp:forward> tag is used to forward a request to
another page
The control will be given to the target page
The syntax of the tag is as follows
Static url or computed at request time.
<jsp:forward page = “Relative url” />
<jsp:forward page = “<%=java expression %>” />
We can pass parameters to the forwarded page using <jsp:param> tag
The syntax of using the jsp:param tag is as follows
<jsp:forward page = “url”>
<jsp:param name = “name” value = “value” />
</jsp:forward>
52. CS3002
Lecture 1 / Slide 52
Standard Actions - jsp:include
The <jsp:include> tag is used to include the contents of
another file in a JSP
The syntax of the tag is as follows
<jsp:include page = “Relative url” />
Unlike the include page directive that pastes the contents
of the included file as a part of the JSP, the <jsp:include>
tag acts at run time i.e., This action inserts the file at the time
the page is requested but not at the time the JSP page is
translated into a servlet as like Action Directives
If the included file is modified, the next request will receive
the modified content in the case of <jsp:include>
EX: MyCompanyHome, StockPrice
53. CS3002
Lecture 1 / Slide 53
why java beans in jsp
A JavaBean can be defined as a reusable software component
write a JavaBean that can then be used in a variety of other Java
based softwares such as applications, Servlets or JSP pages.
we can define our business logic within a JavaBean and then
consistently use that logic in seperate applications.
3 ways of writing code to be used by a JSP. These are,
1. Place the code at the start of a JSP in a declaration,
2. Use an include statement to reference another file which
contains the code and now
3. Package the code in a JavaBean (JavaBeans you can fully
separate the business logic from the generation of the display.)
54. CS3002
Lecture 1 / Slide 54
Standard Actions - jsp:useBean, jsp:setProperty,
jsp:getProperty
Minimizing Java code in a JSP will enable even a web
designer to maintain it
To separate presentation from code, we can encapsulate the
logic in a JavaBean
JSP can instantiate a JavaBean using the <jsp:useBean> tag,
set the bean properties using the <jsp:setProperty> tag and
get the bean properties using the <jsp:getProperty> tag
syntax:
<jsp:useBean id="name" class="package.class" />
Attributes: id, class, scope, type, beanName
scope: page | request | session | application
55. CS3002
Lecture 1 / Slide 55
Bean Class
package hall;
public class SimpleBean
{
private String message = “Hello, Chakradhar";
public String getMessage()
{ return(message); }
public void setMessage(String message)
{ this.message = message; }
}
56. CS3002
Lecture 1 / Slide 56
Bean laws
public no-arg constructor
public getter and setter methods. “get” and “set” followed
by same word. property name is derived by changing first
character to lowercase.
Setter argument type and getter return type must be identical
You have a property because you have getter and setter
methods
For use with JSPs property type should be String or
primitive. If it isn’t you can’t rely on standard actions and
you might have to use scripting
59. CS3002
Lecture 1 / Slide 59
Standard Actions - jsp:useBean
The <jsp:useBean> tag can be used to create a bean
object
The important attributes of <jsp:useBean> tag are
id
class
scope
The id attribute
Specifies the name of the Bean object
The class attribute
Specifies the fully qualified name of the Bean class
60. CS3002
Lecture 1 / Slide 60
Standard Actions - jsp:useBean
The scope attribute
Specifies the scope of the Bean object as page, request,
session or application
The page scope
Available only for this request and only in this page
By default, the scope will be page
The request scope
Available only for this request
Available to other forwarded and included JSPs
The session scope
Available to the current session
The application scope
Available to any JSP in the same application
61. CS3002
Lecture 1 / Slide 61
Standard Actions - jsp:useBean
The <jsp:useBean> tag for instantiating the WishBean
is as follows
<jsp:useBean id = "myWishBean" class =
“mypackage.WishBean"/>
The above tag is equivalent to the following Java code
mypackage.WishBean myWishBean = new mypackage.WishBean();
62. CS3002
Lecture 1 / Slide 62
jsp:setProperty
It is used to sets values to properties of beans in two ways
1. use it after, but outside of a jsp:useBean element, which is
executed regardless of whether a new bean was instantiated or an
existing bean was found.
<jsp:useBean id="myName" .../ >...
<jsp:setProperty name="myName” property=“anyProperty”… />
2. appears inside the body of a jsp:useBean element, which is
executed only if a new object was instantiated, not if an existing
one was found.
<jsp:useBean id="myName" ... > ...
<jsp:setProperty name="myName” property=“anyProperty”… />
</jsp:useBean>
63. CS3002
Lecture 1 / Slide 63
Standard Actions - jsp:setProperty
The <jsp:setProperty> tag can be used to set the Bean
properties
The attributes are
name
property
param
value
The name attribute
Specifies the id of the Bean object
64. CS3002
Lecture 1 / Slide 64
Standard Actions - jsp:setProperty
The property attribute
Specifies the name of the bean property that is to be set
If this attribute is *, all the request parameters will be
assigned to bean properties based on matching name
If the request parameter is having a value “”, the bean
property is left unaltered
The param attribute
Specifies the name of the request parameter whose value is to
be put in to the bean property
If this value is not specified, the value of the request
parameter whose name is same as that of the bean property
will be assigned to the bean property
65. CS3002
Lecture 1 / Slide 65
<jsp:setProperty>
<jsp:useBean … >
<jsp:setProperty name=”person” property=”name” param=”username” />
</jsp:useBean>
<input type=”text” name=”name”>
<jsp:useBean … >
<jsp:setProperty name=”person” property=”name” />
</jsp:useBean>
If ALL the request parameter names match with the bean property names then
<jsp:useBean … >
<jsp:setProperty name=”person” property=”*” />
</jsp:useBean>
66. CS3002
Lecture 1 / Slide 66
Standard Actions - jsp:setProperty
The value attribute
Specifies the value to be assigned to the bean property
<jsp:setProperty name=“myWishBean”
property=“wish” value=“Welcome” />
The above tag is equivalent to the following Java code
myWishBean.setWish(“Welcome”);
A tag cannot have both param and value attributes together
The <jsp:setProperty tag to set the bean property wish
of WishBean to the value Welcome is as follows
67. CS3002
Lecture 1 / Slide 67
<jsp:setProperty>
String to primitive doesn’t work with following
<jsp:setProperty name=”person” property=”empID”
value=”<%=request.getParameter(“empID”)%>” />
But works with
<jsp:setProperty name=”person” property=”*” />
<jsp:setProperty name=”person” property=”empID” />
<jsp:setProperty name=”person” property=”empID” value=”343” />
<jsp:setProperty name=”person” property=”empID” param=”empID” />
68. CS3002
Lecture 1 / Slide 68
jsp:getProperty
This element retrieves the value of a bean property,
converts it to a string, and inserts it into the output.
The two required attributes are name of a bean, and
property whose value should be inserted.
<jsp:useBean id="itemBean" ... />...
<UL>
<LI>Number of items:
<jsp:getProperty name="itemBean" property="numItems" />
<LI>Cost of each:
<jsp:getProperty name="itemBean" property="unitCost" />
</UL>
69. CS3002
Lecture 1 / Slide 69
Standard Actions - jsp:getProperty
The <jsp:getProperty> tag can be used to get the value
of a bean property
The attributes are
name
property
The name attribute
Specifies the id of the Bean object
The property attribute
Specifies the name of the bean property to get
70. CS3002
Lecture 1 / Slide 70
Standard Actions - jsp:getProperty
The <jsp:getProperty> can be used to get the property
wish of the WishBean as follows
<jsp:getProperty name =
"myWishBean" property = "wish" />
The above tag is equivalent to the following Java
code
myWishBean.getWish();
73. CS3002
Lecture 1 / Slide 73
Setting attributes at various scopes
Servlet JSP
Application getServletContext(). application.setAttribute(“foo”,barObj);
setAttribute(“foo”,barObj);
Request request.setAttribute(“foo”,barObj); request.setAttribute(“foo”,barObj);
Session request.getSession(). session.setAttribute( “foo”,barObj);
setAttribute(“foo”,barObj);
Page Does not apply pageContext.setAttribute(“foo”,barObj);
PageContext extends JspContext
APPLICATION_SCOPE //static final fields
PAGE_SCOPE
REQUEST_SCOPE
SESSION_SCOPE
Methods of JspContext
getAttribute(String name, int scope)
setAttribute(String name,Object obj,int scope)
74. CS3002
Lecture 1 / Slide 74
Custom Actions
In JSP, the programmer can create her own customized
tags to encapsulate code from presentation
These tags are categorized as Custom Actions
The syntax of using custom actions is as follows
<prefix:name />
Each custom tag will have an implementation class
where the actual Java code resides
When the JSP Container comes across a custom tag,
the code in the implementation class is executed
However, the code will be hidden from the JSP page
75. CS3002
Lecture 1 / Slide 75
The Tag interface
The implementation class of a custom tag should
implement javax.servlet.jsp.jspext.Tag interface
Two important methods of the Tag interface are as
follows
public int doStartTag() throws javax.servlet.jsp.JspException
public int doEndTag() throws javax.servlet.jsp.JspException
public int doAfterBody() throws javax.servelt.jsp.JspException
These methods are automatically executed when the
JSP encounters the starting tag and ending tag of the
custom tag
77. CS3002
Lecture 1 / Slide 77
The Tag interface
The Tag interface has the following final static int fields
EVAL_BODY_INCLUDE SKIP_BODY
EVAL_PAGE SKIP_PAGE
EVAL_BODY_AGAIN
The doStartTag() method can return
– EVAL_BODY_INLCUDE so that JSP continues evaluating the body of
the tag
– SKIP_BODY so that JSP skips evaluating the body of the tag
The doEndTag() method can return
– EVAL_PAGE so that JSP continues evaluating the rest of the page
– SKIP_PAGE so that JSP skips evaluating the rest of the page
The doAfterBody() method can return
– EVAL_BODY_AGAIN so that JSP continues evaluating the body of
the tag
– SKIP_BODY so that JSP skips evaluating the body of the tag
78. CS3002
Lecture 1 / Slide 78
The TagSupport class
The TagSupport class implements the Tag interface
and provides blank implementation for all the methods
It is easy to extend TagSupport than to implement Tag
The doStartTag(), doAfterBody() and doEndTag()
methods of TagSupport class return SKIP_BODY,
SKIP_BODY and EVAL_PAGE respectively.
79. CS3002
Lecture 1 / Slide 79
The PageContext class
A protected object of type javax.servlet.jsp.PageContext
called pageContext is declared in the TagSupport class
This object can be used to get many attributes of the
page like the out, response, request and session objects
Eg: JspWriter out= pageContext.getOut();
Some important methods of the PageContext class is as
follows
public abstract JspWriter getOut()
public abstract ServletRequest getRequest()
public abstract ServletResponse getResponse()
public abstract HttpSession getSession()
80. CS3002
Lecture 1 / Slide 80
Tag handler class
.tld file public class SimpleTagTest1 extends
<taglib > TagSupport {
<tlib-version>1.2</tlib-version> private List movieList;
<uri>simpleTags</uri> public void setMovieList(List
<tag> movieList) {
<description> simple </description> this.movieList=movieList;
<name>simple1</name> }
<tag-class>foo.SimpleTagTest1</tag-class> public void doStartTag throws
<body-content>empty</body-content> JSPException{
<attribute> try {
<name>movieList</name> Iterator i= movieList.iterator();
<required>true</required> for …
<rtexprvalue>true</rtexprvalue> } catch(IOException e) {
</attribute> throw new
JspException(“IO”+e.toString());
</tag>
}
}}
82. CS3002
Lecture 1 / Slide 82
The taglib Directive
Tag Library Descriptor or TLD is an xml file that
describes a custom tag
Ex: HelloWorldTag.tld
The taglib directive is used to tell the JSP the location
of TLD
<%@ taglib uri=“HelloWorldTag.tld" prefix="tagexample" %>
tagdir=“/WEB-
<%@ taglib tagdir=“/WEB-INF/tlds/HelloWorldTag.tld"
prefix="tagexample" %> used in a JSP as follows
The custom tag can be
<tagexample:helloworld />
83. CS3002
Lecture 1 / Slide 83
The helloworld Custom Tag
Ex: HelloWorldTagTestJSP
84. CS3002
Lecture 1 / Slide 84
The emplist Custom Tag
Ex: EmpList
EmpListTag.tld
EmpListTagLibTestJSP
85. CS3002
Lecture 1 / Slide 85
The hellouser Custom Tag
Custom Tags can accept attributes and behave
according to their value
The TLD file should contain the information about
these attributes
Ex: HelloUser
HelloUserTag.tld
HelloUserTagLibTestJSP
86. CS3002
Lecture 1 / Slide 86
Expression Language
EL makes nested properties easy to print.
JSP supports Expression Language to create a “scriptless”
JSP
${param.name}
Expression Language or EL provides simpler syntax and
implicit objects to perform some of the actions that could
be performed by scriptlets
– The above EL expression is equivalent to the following scriptlet
request.getParameter(“name”)
87. CS3002
Lecture 1 / Slide 87
EL implicit objects
pageScope //map of scope attirbutes
requestScope
sessionScope
applicationScope
param // map of request parameters
paramValues
header //map of request headers
headerValues
cookie
initParam //map of context init parameters, not servlet
initParameters
pageContext //bean
88. CS3002
Lecture 1 / Slide 88
EL
${person.name} same as ${person[“name”] }
Person can be bean or map. Name is property or key
If person is array or list, above doesn’t work
String[] favMusic= {“zero 7”,”tah 80”,” frou frou” };
request.setAttribute(“musicList”, favMusic);
If musicList refers to an array.
First song: ${musicList[0]} // ${musicList.0} doesn’t work
Second song : ${musicList[“1”]}
${param.name} ${paramValues.name[0]}
${request.method} //doesn’t works
${requestScope.method} //works
<content-param><param-name>..</..> <param-value> </..> </context-param>
${initParam.email}
EL functions: ${param:fun()}
89. CS3002
Lecture 1 / Slide 89
JSP Standard Tag Library - JSTL
Many developers creating tag libraries were duplicating
many actions as these libraries were created separately
There was a need for standardizing the tag libraries, and JSP
Standard Tag Library (JSTL) was created based on this
JSTL provides a rich set of tags that helps the web designers
to perform various actions like
iterate over each item in a Collection
format
process xml
access database
Application programmers rarely create custom tags and
instead use the powerful JSTL and other open source tag
libraries
91. CS3002
Lecture 1 / Slide 91
JSTL tags
Some absolute URIs are given for the JSTL library are as follows:
For core: http://java.sun.com/jsp/jstl/core
For XML: http://java.sun.com/jsp/jstl/xml
For Internationalization(date format & currency format):
http://java.sun.com/jsp/jstl/fmt
For SQL: http://java.sun.com/jsp/jstl/sql
For Functions: http://java.sun.com/jsp/jstl/functions
core <c: />
xml <xml: />
sql <sql: />
formatting <fmt: />
functions <fn: />
95. CS3002
Lecture 1 / Slide 95
<c:forEach>
<c:forEach> action tag contain the following attribute list:
items : the collection of items like String[]
var : a symbolic name for the collection
begin : the starting index of iteration
end : the ending index of iteration
step : incremental step
varStatus: symbolic name for current status.
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:forEach var="n" begin="3" end="8" >
<c:out value="${n}" /> <br>
</c:forEach>
100. CS3002
Lecture 1 / Slide 100
JSTL- XML
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix=“x" >uri="http://java.sun.com/jstl/xml" %>
<html> <body>
<c:import url="books.xml" var="url" />
<x:parse xml="${url}" var="doc" />
<table border=1> <th> <tr> <td>title</td> <td>author</td> </tr> </th>
<x:forEach var="n" select="$doc/books/book">
<tr>
<td> <x:out select="$n/title" /></td>
<td> <x:out select="$n/author" /></td>
</tr> Title Author
</x:forEach> Cobol Roy
</table> </body> </html> Java Herbert
We have given a symbolic name for this file as 'url‘ Xml unleashed morrison
The resulting tree is given a symbolic name as 'doc'.
Magically, we have parsed a given XML document and extracted information,
without any mention about DOM,SAX and such words.
107. CS3002
Lecture 1 / Slide 107
<fn:escapeXml(String)> Tag of JSTL
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html> <head> <title>Example of fn:escapeXml Tag</title> </head> <body>
<c:set var="str1" value="This is first String."/>
<c:set var="str2" value="This <abc>is second String.</abc>"/>
<c:set var="str3" value="<mahendra>This is first String.</mahendra>"/>
<h4>fn:escapeXml</h4>
<table border="1">
<tr> <th>without fn:escapeXml</th> <th>with fn:escapeXml</th> </tr>
<tr> <td>${str1}</td> <td> ${fn:escapeXml(str1)} </td> </tr>
<tr> <td>${str2}</td> <td> ${fn:escapeXml(str2)} </td> </tr>
<tr> <td>${str3}</td> <td> ${fn:escapeXml(str3)} </td> </tr>
</table> </body> </html>
108. CS3002
Lecture 1 / Slide 108
Summary
JSP is a technology for coding the presentation logic of
an enterprise application
Web designers without programming skills can create
and maintain JSP
The Standard Actions and Custom Actions help to
encapsulate the code from presentation
Rich, Open Source, Standard Tag Libraries are
available