CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 11
CS3002
Software TechnologiesSoftware Technologies
Lecture 12
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 22
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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 33
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 technologyweb 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 44
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 � Unlike HTML files, JSP files will contain some Java code also with in <% %> tags
� Ex: LongMessageJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 55
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, � 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 66
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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 77
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 browserthe browser
� Starting from the second request, there is no overhead
of compilation
CLIEN
TJSP
SERVLET
COMPILE
IS
VALID
?
Request
Text
Class
Response
No
Yes
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 88
JSP
� Ex: LongMessageJSP_jsp.java
� In Netbeans its found under,
Webapplication folder -> build -> generated -> src -> org -> apache -> jsp -> LongMessageJSP_jsp.java-> apache -> jsp -> LongMessageJSP_jsp.java
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 99
Implicit Objects� A JSP developer can use some implicit objects
� 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1010
� Directives //no output to client
� page
� include
� taglib
� Scripting elements
� Scriptlet� Scriptlet
� Declaration
� expression
� Standard actions
� forward
� include
� useBean
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1111
Implicit Objects - Example � This example uses the out, request and session objects
� Ex: SessionTestJSPForm.html
� SessionTestJSP
� ReadSessionTestJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1212
JSP tagsSCRIPTING TAGS
DIRECTIVE TAGS
ACTION TAGS
CUSTOM TAGSCUSTOM TAGS
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1313
Tags in JSP
� Tags in JSP can be categorized as
� Comments
� Scripting elements
� Directive 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1414
Comments� Just like any other HTML tag, standard HTML
comment tag also can be used in JSP
<!<!<!<!-------- This is a comment in HTML This is a comment in HTML This is a comment in HTML This is a comment in HTML -------->>>>
This comment tag will reach the browser
This comment tag will not reach the browser
This comment tag will reach the browser
A JSP specific comment tag is written as follows
<%<%<%<%-------- This is a JSP Comment This is a JSP Comment This is a JSP Comment This is a JSP Comment --------%>%>%>%>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1515
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 \" To get a double quote in an attribute \"
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1616
Scripting tags
SCRIPTING TAGS are three types
SCRIPTLET TAGS
EXPRESSION TAGS
DECLARATION TAGS
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1717
Scripting Elements
� Scripting elements are elements in the page that include
the Java code
� JSP can contain 3 types of scripting elements
� Scriptlets <% %>� Scriptlets <% %>
� Declarations <%! %>
� Expressions <%= %>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1818
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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 1919
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;int data;int data;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;double amount;double amount;double amount;
%>%>%>%>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2020
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 Servletgenerated Servlet
� Ex: MethodTestJSPForm.html
� MethodTestJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2121
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>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2222
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> </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>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2323
Validating using javascript in jsp….
<% if(ent==0)
String insertQry = "insert Employee values('"+code+"','"+empname+"')";
int val = stmt.executeUpdate(insertQry);
%>
<script language="javascript">
alert("Insertion successful");alert("Insertion successful");
document.location="EmplyeeInformation.jsp";
</script>
<% } if(ent==1) { %>
<script language="javascript">
alert("This Emp ID already Exists");
document.location="EmplyeeInformation.jsp";
</script> <% } stmt.close(); con.close(); }
catch(Exception e) {
out.println(e.toString());
}
%>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2424
Initialization parameters
<servlet>
<servlet-name>MyTestInit</servlet-name>
<jsp-file>/TestInit.jsp</jsp-file>
<init-param><init-param>
<param-value>name</param-name>
<param-value>abc</param-value>
</init-param>
</servlet>
web.xml
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2525
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� 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2626
JSP Lifecycle
� javax.servlet.jsp.JspPage
methods jspInit(), jspDestroy()
� javax.servlet.jsp.HttpJspPage extends � javax.servlet.jsp.HttpJspPage extends
javax.servlet.jsp.JspPage
methods
_ jspService(HttpServletRequest,HttpServletResponse)
// can’t override this!!!
Ex: LifecycleTestJSPForm.html, LifecycleTestJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2727
Scripting Elements - Expressions
� The value of an expression can be printed to the
browser using the syntax <%=expression%>
<%<%<%<%
String name = “Software”;String name = “Software”;String name = “Software”;String name = “Software”;
%>%>%>%>%>%>%>%>
Hello <%=name%>Hello <%=name%>Hello <%=name%>Hello <%=name%>
� These expressions doesn’t end with semi-colon. These
are passed as argument to out.print()
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2828
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> 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>
<% } %>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 2929
Servlet and JSPString 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);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>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3030
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");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");
} %>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3131
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;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`) );
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3232
Retrieving data from a file<%@ page import="java.io.*"%>
<html><body>
<%
String fName = "c:\\csv\\myfile.csv";
String thisLine; int count=0; int i=0;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis); %>
<table><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>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3333
Export data to a file from database
http://www.roseindia.net/jsp/jdbccsv.shtml
Downloading a file from databaseDownloading a file from database
http://www.roseindia.net/jsp/downloadcsv.shtml
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3434
Reading request information
� <%= request.getMethod() %>
� <%= request.getRequestURI() %>
� <%= request.getProtocol() %>
� <%= request.getQueryString() %>� <%= request.getQueryString() %>
� <%= request.getContentType() %>
� <%= request.getServerName() %>
� <%= request.getRemoteUser() %>
� …
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3535
Retrieving data posted to a jsp file
from html file
� <input type=“text” name=“username” size=“20”>
<html><body><html><body>
<%=request.getParameter(“username”) %>
</body></html>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3636
Directive tags
DIRECTIVE TAGS are three types
PAGE DIRECTIVE
INCLUDE DIRECTIVE
TAGLIB DIRECTIVE
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3737
Directive Elements
� Directive elements provide information to the JSP
container about the page
� JSP can contain three types of directives
� page
include� include
� taglib
� Syntax
<<%@ directive attribute="value" %> %>
<<%@ directive attribute1="value1“ attribute2="value2“
...attributeN="valueN" %>%>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3838
The page Directive� The page directive has the following form
<%@ page attributes %><%@ page attributes %><%@ page attributes %><%@ page attributes %>
� Some of the important attributes are
� import
� session
� contentType
� errorPage
� isErrorPage
� isThreadSafe, isELIgnored, language, extends,
session, buffer, autoFlush, info, pageEncoding
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 3939
The page Directive - import
The import attribute
– Example
<%@ page import = “java.io.*,java.net.Socket” %><%@ page import = “java.io.*,java.net.Socket” %><%@ page import = “java.io.*,java.net.Socket” %><%@ 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!!
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4040
The page Directive - session
� The session attribute
� Example
<%@ page session = “false” %><%@ page session = “false” %><%@ page session = “false” %><%@ 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4141
The page Directive - contentType� The contentType attribute
� Example
<%@ page contentType = “text/plain” %><%@ page contentType = “text/plain” %><%@ page contentType = “text/plain” %><%@ page contentType = “text/plain” %>
� The contentType of the response can be set using � The contentType of the response can be set using
the appropriate MIME type
� The default value is “text/html”
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4242
The page Directive - errorPage
� The errorPage attribute
� Example
<%@ page errorPage = “Error.jsp” %><%@ page errorPage = “Error.jsp” %><%@ page errorPage = “Error.jsp” %><%@ page errorPage = “Error.jsp” %><%@ page errorPage = “Error.jsp” %><%@ page errorPage = “Error.jsp” %><%@ page errorPage = “Error.jsp” %><%@ 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4343
The page Directive - isErrorPage
<%@ page isErrorPage = “true” %><%@ page isErrorPage = “true” %><%@ page isErrorPage = “true” %><%@ page isErrorPage = “true” %>
The isErrorPage attribute
– Example
� 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
<%@ page isErrorPage = “true” %><%@ page isErrorPage = “true” %><%@ page isErrorPage = “true” %><%@ page isErrorPage = “true” %>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4444
The page Directive - errorPage and isErrorPage
� Ex: ErrorTestPageJSP
� ErrorPageJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4545
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" %><%@ include file = "../Header.html" %><%@ include file = "../Header.html" %><%@ 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4646
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� Header.html
� Footer.html
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4747
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:
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4848
Action tags
ACTION TAGS are three types
FORWARD ACTION
INCLUDE ACTION
USEBEAN ACTION
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 4949
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� Some common standard actions are
� <jsp:forward>
� <jsp:include>
� <jsp:useBean>
� <jsp:setProperty>
� <jsp:getProperty>
� <jsp:param>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5050
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 followsThe syntax of the tag is as follows
� Static url or computed at request time.<jsp:forward page = “Relative url” /><jsp:forward page = “Relative url” /><jsp:forward page = “Relative url” /><jsp:forward page = “Relative url” />
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:forward page = “url”><jsp:forward page = “url”><jsp:forward page = “url”>
<jsp:param name = “name” value = “value” /><jsp:param name = “name” value = “value” /><jsp:param name = “name” value = “value” /><jsp:param name = “name” value = “value” />
</jsp:forward></jsp:forward></jsp:forward></jsp:forward>
<jsp:forward page = “<%=java expression %>” /><jsp:forward page = “<%=java expression %>” /><jsp:forward page = “<%=java expression %>” /><jsp:forward page = “<%=java expression %>” />
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5151
Standard Actions - jsp:forward
� Ex: BusinessLogicJSPForm.html
� BusinessLogicJSP
� PresentationJSP� PresentationJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5252
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” /><jsp:include page = “Relative url” /><jsp:include page = “Relative url” /><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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5353
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.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.)
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5454
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, � 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5555
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; }
}
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5656
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.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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5757
UseBean Action
<HTML><BODY>
<jsp:useBean id="test” class="hall.SimpleBean" />
<jsp:setProperty name="test” property="message“ value="Hello WWW"
/>
<H1> Message: <H1> Message:
<jsp:getProperty name="test“ property="message" />
</H1>
</BODY></HTML>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5858
The WishBean
� Ex: WishBean
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 5959
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� 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6060
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� 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6161
Standard Actions - jsp:useBean
� The <jsp:useBean> tag for instantiating the WishBean
is as follows
<jsp:useBean id = "myWishBean" class = <jsp:useBean id = "myWishBean" class = <jsp:useBean id = "myWishBean" class = <jsp:useBean id = "myWishBean" class = “mypackage.WishBean"/>“mypackage.WishBean"/>“mypackage.WishBean"/>“mypackage.WishBean"/>“mypackage.WishBean"/>“mypackage.WishBean"/>“mypackage.WishBean"/>“mypackage.WishBean"/>
The above tag is equivalent to the following Java code
mypackage.WishBean myWishBean = new mypackage.WishBean();mypackage.WishBean myWishBean = new mypackage.WishBean();mypackage.WishBean myWishBean = new mypackage.WishBean();mypackage.WishBean myWishBean = new mypackage.WishBean();
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6262
jsp:setPropertyIt 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>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6363
Standard Actions - jsp:setProperty
� The <jsp:setProperty> tag can be used to set the Bean
properties
� The attributes are
� name� name
� property
� param
� value
� The name attribute
� Specifies the id of the Bean object
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6464
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 unalteredproperty 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6565
<jsp:setProperty>
<jsp:useBean … >
<jsp:setProperty name=”person” property=”name” param=”username” />
</jsp:useBean>
<input type=”text” name=”name”><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>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6666
Standard Actions - jsp:setProperty� The value attribute
� Specifies the value to be assigned to the bean property
<jsp:setProperty name=“myWishBean” <jsp:setProperty name=“myWishBean” <jsp:setProperty name=“myWishBean” <jsp:setProperty name=“myWishBean” property=“wish” value=“Welcome” />property=“wish” value=“Welcome” />property=“wish” value=“Welcome” />property=“wish” value=“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
The above tag is equivalent to the following Java code
myWishBean.setWish(“Welcome”);myWishBean.setWish(“Welcome”);myWishBean.setWish(“Welcome”);myWishBean.setWish(“Welcome”);
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6767
<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” />
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6868
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>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 6969
Standard Actions - jsp:getProperty
� The <jsp:getProperty> tag can be used to get the value
of a bean property
� The attributes are
� name� name
� property
� The name attribute
� Specifies the id of the Bean object
� The property attribute
� Specifies the name of the bean property to get
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7070
Standard Actions - jsp:getProperty
� The <jsp:getProperty> can be used to get the property
wish of the WishBean as follows
<jsp:getProperty name = <jsp:getProperty name = <jsp:getProperty name = <jsp:getProperty name = "myWishBean" property = "wish" />"myWishBean" property = "wish" />"myWishBean" property = "wish" />"myWishBean" property = "wish" />
The above tag is equivalent to the following Java The above tag is equivalent to the following Java
code
myWishBean.getWish();myWishBean.getWish();myWishBean.getWish();myWishBean.getWish();
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7171
Standard Actions - jsp:useBean,
jsp:setProperty, jsp:getProperty
� Ex: BeanTagTestJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7272
Standard Actions - jsp:useBean,
jsp:setProperty, jsp:getProperty
� Ex: Employee
� EmployeeBeanTestJSPForm.html
� EmployeeBeanTestJSP� EmployeeBeanTestJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7373
Setting attributes at various scopes
Servlet JSP
Application getServletContext().
setAttribute(“foo”,barObj);
application.setAttribute(“foo”,barObj);
Request request.setAttribute(“foo”,barObj); request.setAttribute(“foo”,barObj);
Session request.getSession().
setAttribute(“foo”,barObj);
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)
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7474
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 /><prefix:name /><prefix:name /><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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7575
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 � Two important methods of the Tag interface are as
follows
public int doStartTag() throws javax.servlet.jsp.JspExceptionpublic int doStartTag() throws javax.servlet.jsp.JspExceptionpublic int doStartTag() throws javax.servlet.jsp.JspExceptionpublic int doStartTag() throws javax.servlet.jsp.JspException
public int doEndTag() throws javax.servlet.jsp.JspExceptionpublic int doEndTag() throws javax.servlet.jsp.JspExceptionpublic int doEndTag() throws javax.servlet.jsp.JspExceptionpublic int doEndTag() throws javax.servlet.jsp.JspException
public int doAfterBody() throws javax.servelt.jsp.JspExceptionpublic int doAfterBody() throws javax.servelt.jsp.JspExceptionpublic int doAfterBody() throws javax.servelt.jsp.JspExceptionpublic 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7676
Tag handler execution
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7777
The Tag interface� The Tag interface has the following final static int fields
The doStartTag() method can return
– EVAL_BODY_INLCUDE so that JSP continues evaluating the body of
EVAL_BODY_INCLUDEEVAL_BODY_INCLUDEEVAL_BODY_INCLUDEEVAL_BODY_INCLUDE SKIP_BODYSKIP_BODYSKIP_BODYSKIP_BODY
EVAL_PAGEEVAL_PAGEEVAL_PAGEEVAL_PAGE SKIP_PAGESKIP_PAGESKIP_PAGESKIP_PAGE
EVAL_BODY_AGAINEVAL_BODY_AGAINEVAL_BODY_AGAINEVAL_BODY_AGAIN
– 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7878
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,The doStartTag(), doAfterBody() and doEndTag() methods of TagSupport class return SKIP_BODY,SKIP_BODY and EVAL_PAGE respectively.
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 7979
The PageContext class� A protected object of type javax.servlet.jsp.PageContextcalled 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 � Some important methods of the PageContext class is as follows
public abstract JspWriter getOut()public abstract JspWriter getOut()public abstract JspWriter getOut()public abstract JspWriter getOut()
public abstract ServletRequest getRequest()public abstract ServletRequest getRequest()public abstract ServletRequest getRequest()public abstract ServletRequest getRequest()
public abstract ServletResponse getResponse()public abstract ServletResponse getResponse()public abstract ServletResponse getResponse()public abstract ServletResponse getResponse()
public abstract HttpSession getSession()public abstract HttpSession getSession()public abstract HttpSession getSession()public abstract HttpSession getSession()
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8080
.tld fileTag handler class
public class SimpleTagTest1 extends
TagSupport {
private List movieList;
public void setMovieList(List
movieList) {
this.movieList=movieList;
}
<taglib >
<tlib-version>1.2</tlib-version>
<uri>simpleTags</uri>
<tag>
<description> simple </description>
<name>simple1</name>
public void doStartTag throws
JSPException{
try {
Iterator i= movieList.iterator();
for …
} catch(IOException e) {
throw new
JspException(“IO”+e.toString());
}
} }
<tag-class>foo.SimpleTagTest1</tag-class>
<body-content>empty</body-content>
<attribute>
<name>movieList</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8181
The helloworld Custom Tag
� Ex: HelloWorld
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8282
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 The taglib directive is used to tell the JSP the location
of TLD
<%@ taglib uri=“HelloWorldTag.tld" prefix="tagexample" %><%@ taglib uri=“HelloWorldTag.tld" prefix="tagexample" %><%@ taglib uri=“HelloWorldTag.tld" prefix="tagexample" %><%@ taglib uri=“HelloWorldTag.tld" prefix="tagexample" %>
The custom tag can be used in a JSP as follows
<tagexample:helloworld /><tagexample:helloworld /><tagexample:helloworld /><tagexample:helloworld />
<%@ taglib tagdir=“/WEB<%@ taglib tagdir=“/WEB<%@ taglib tagdir=“/WEB<%@ taglib tagdir=“/WEB----INF/tlds/HelloWorldTag.tld" INF/tlds/HelloWorldTag.tld" INF/tlds/HelloWorldTag.tld" INF/tlds/HelloWorldTag.tld" prefix="tagexample" %>prefix="tagexample" %>prefix="tagexample" %>prefix="tagexample" %>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8383
The helloworld Custom Tag
� Ex: HelloWorldTagTestJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8484
The emplist Custom Tag
� Ex: EmpList
� EmpListTag.tld
� EmpListTagLibTestJSP� EmpListTagLibTestJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8585
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� Ex: HelloUser
� HelloUserTag.tld
� HelloUserTagLibTestJSP
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8686
Expression Language� EL makes nested properties easy to print.
� JSP supports Expression Language to create a “scriptless”
JSP
${param.name}${param.name}${param.name}${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”)request.getParameter(“name”)request.getParameter(“name”)request.getParameter(“name”)
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8787
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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8888
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()}
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 8989
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 liketo 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
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9090
<%@ taglib prefix=“c” uri=“http://java.sun.com/jstl/core”%>
<c:set var=“a” value=“sam” />
<c:out value=“${a}” />
String s=request.getParameter(“text1”);
same as
<c:set var=“s” value=“${param.text1}” >
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9191
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/fmthttp://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: />
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9292
Core tags
� <c:set
� <c:out
� <c:if
� <c:choose, <c:when , <c:otherwise� <c:choose, <c:when , <c:otherwise
� <c:foreach
� <c:forTokens
� <c:import
� <c:url
� <c:redirect
� <c:param
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9393
<c:if><%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html><body>
<form method=post action=demo3.jsp>
<select name="combo1">
<option value="sam">sam
<option value="tom">tom
</select>
<input type=submit> <input type=submit>
</form>
<c:set var="s" value="${param.combo1}" />
<c:out value="${s}" /> <br>
<c:if test="${s eq 'sam' }" >
<c:out value="Good Morning...SAM!" />
</c:if>
<c:if test="${s = = 'tom'}" >
<c:out value=" How Are You?....TOM!" />
</c:if> </body> </html>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9494
<c:choose., <c:when> , <c:otherwise><%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html> <body bgcolor=lightblue>
<form method=post action="demo3.jsp">
<select name="combo1">
<option value="1">1 </option> <option value="2">2 </option>
<option value="3">3 </option> <option value="4">4 </option>
<option value="5">5 </option> <option value="7">7 </option>
</select> </select>
<input type=submit>
<c:set var="s" value="${param.combo1}" />
Today is <font size=24 color=red>
<c:choose>
<c:when test="${s==1}">Sunday </c:when>
<c:when test="${s==2}">Monday</c:when>
<c:when test="${s==3}">Tuesday</c:when>
<c:when test="${s==4}">Wednesday</c:when>
<c:when test="${s==5}">Thursday</c:when>
<c:otherwise> select between 1 & 5 </c:otherwise>
</c:choose> </body> </html>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9595
<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. 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>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9696
<c:import>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:import url="welcome.htm"/>
<c:out value="to our web-site!" />
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9797
<c:url>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<a href= "<c:url value="http://localhost:8080/welcome.htm/>">
send </a>
� Url encoding
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9898
<c:redirect>� <%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:redirect url="http://localhost:8080/welcome.htm />
Redirecting to the url
� <%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:redirect url="http://localhost:8080/jstldemos/core/sample.jsp" >
<c:param name="name1" value="SAM"/>
</c:redirect>
passing parameters to sample.jsp
� sample.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:out value="${param.name1}"/>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 9999
books.xml
� <?xml version="1.0" ?>
<books>
<book>
<title>cobol</title>
<author>roy</author>
</book>
<book> <book>
<title>java</title>
<author>herbert</author>
</book>
<book>
<title>xml unleashed</title>
<author>morrison</author>
</book>
</books>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 100100
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>
</x:forEach>
</table> </body> </html>
� We have given a symbolic name for this file as 'url‘
� 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.
Title Author
Cobol Roy
Java Herbert
Xml unleashed morrison
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 101101
students.xml<?xml version="1.0"?>
<students>
<student>
<name>Thomas</name>
<place>Delhi</place>
<number>1111</number>
<mark>78</mark>
</student> </student>
<student>
<name>David</name>
<place>Bombay</place>
<number>4444</number>
<mark>90</mark>
</student>
</students>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 102102
xsl1.xsl
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html> <body> <table border="2" bgcolor="yellow">
<tr> <th>Name</th> <th>Place</th> <th>Number</th> <th>Mark</th> </tr>
<xsl:for-each select="students/student">
<tr>
<td><xsl:value-of select="name"/> </td>
<td><xsl:value-of select="place"/> </td>
<td><xsl:value-of select="number"/> </td>
<td><xsl:value-of select="mark"/> </td>
</tr>
</xsl:for-each>
</table> </body> </html>
</xsl:template>
</xsl:stylesheet>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 103103
Transforming xml to xsl using JSTL
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
<c:import url="students.xml" var="url" />
<c:import url="xsl1.xsl" var="xsl" />
<x:transform xml="${url}" xslt="${xsl}" />
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 104104
JSTL sql tags
<html>
<body>
<form method=post action="query.jsp">
<textarea name='area1' rows=10 cols=30>
</textarea>
<input type=submit> <input type=submit>
</form>
</body>
</html>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 105105
query.jsp<%@ taglib prefix="c" %>uri="http://java.sun.com/jstl/core"
<%@ taglib prefix="sql" %> uri="http://java.sun.com/jstl/sql"
<html> <body>
<sql:setDataSource var="db"
driver="sun.jdbc.odbc.JdbcOdbcDriver"
url="jdbc:odbc:dbdemo" />
<c:set var='s' value="${param.area1}" />
<c:out value="${s}" /> <br>
<sql:query var="query1" dataSource="${db}" sql="${s}" />
<table border="1">
<c:forEach var="row" items="${query1.rows}" >
<tr>
<td> <c:out value="${row.name}" /></td>
<td> <c:out value="${row.place}" /></td>
</tr>
</c:forEach> </table> </body> </html>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 106106
Function tags
� <c:out value="${fn:replace(string,find,replaceWith)}"/>
� <c:out value="${fn:indexOf(text,str)}"/>
� <c:forEach var="num" items="${fn:split(str1, ' ')}">
<c:out value="${num}" /> <c:out value="${num}" />
</c:forEach>
� <c:out value="${fn:substring(string,start,end)}"/>
� <c:out value="${fn:substringBefore(fString,sString)}"/>
� <c:out value="${fn:substringAfter(fString,sString)}"/>
� <c:set var="trimText" value="${fn:trim(text)}"/>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 107107
<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="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>
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 108108
Summary
� JSP is a technology for coding the presentation logic of
an enterprise application
� Web designers without programming skills can create
and maintain JSPand maintain JSP
� The Standard Actions and Custom Actions help to
encapsulate the code from presentation
� Rich, Open Source, Standard Tag Libraries are
available
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 109109
References� http://www.roseindia.net/jsp/
� http://www.roseindia.net/jstl/jstlxmltags.shtml
� http://www.roseindia.net/jstl/jstsqlltags.shtml
� http://www.roseindia.net/jsp/implement-javascript-with-jsp.shtml
� http://www.roseindia.net/jsp/loginbean.shtml
� http://www.roseindia.net/jsp/loginstatus.shtml
� http://www.roseindia.net/jsp/DisplayimageonJSPpageusingXML.shtml� http://www.roseindia.net/jsp/DisplayimageonJSPpageusingXML.shtml
� http://www.roseindia.net/jsp/ExampleOfPrintingTextMessage.shtml
� http://www.roseindia.net/jsp/embeddingwmp.shtml
� http://www.roseindia.net/jsp/core-xml-tag.shtml
� http://www.roseindia.net/jsp/parsing-xml.shtml
� http://www.roseindia.net/jsp/applet-jsp.shtml
� http://www.roseindia.net/jsp/add-flash-jsp.shtml
� http://www.gulland.com/courses/JavaServerPages/jsp_beans.jsp
CS3002CS3002
Lecture 1 / Slide Lecture 1 / Slide 110110
Applications
� http://www.roseindia.net/jsp/bank.shtml
� http://www.roseindia.net/jsp/online-quiz-application-
jsp.shtml
� http://www.roseindia.net/jsp/paging.shtml� http://www.roseindia.net/jsp/paging.shtml
� http://www.roseindia.net/jsp/file_upload/uploadingMul
tipleFiles.shtml
� http://www.roseindia.net/jsp/jsp-frameset.shtml