Programming
1
Understanding •Java Server Pages isJSP another technology
defined by Sun Microsystems to generate dynamic web content. •JSP is a form of server-side applications. •They are direct extension of servlets. •They are more efficient than servlets. •JSP is a type of server-side scripting language. •JSP program files have an extension .jsp 2
Understanding JSP which are They are HTML documents
embedded with Java code using different JSP tags. When compared with servlets they are unstructured and contains pieces of java code scattered through out an HTML file.
Since they are server-side applications, they have access to server resources such as servlets, javabeans, Ejbs and databases. 3
Advantages of JSP they allow •JSP’s being Java programs, write-once, run-anywhere policy. •JSP tags are simple to understand, since they are similar to HTML and XML. •Since there is a standard, published API for JSP, and because of Java code portability, use of JSP is independent of hardware, OS or server software.
4
Advantages of JSP JSP being vendor-neutral, developers and system architects can select best-of-breed solutions at all stages of JSP deployment.
It has full access to the underlying J2SE APIs (database access, directory services, distributed computing, cryptography…).
Hence JSP is highly flexible and featurerich to create web-based applications.
5
Advantages of JSP Does not require server restart when the JSP program code changes.
Separation of roles into graphical content and dynamic content.
JSP’s being a modified way of writing servlets, they can provide all features/capabilities of a servlets.
6
JSP History Servlets first appeared as part of Sun’s Java Web Server (JWS), a Java based HTTP server in 1997.
Sun eventually released the Servlet technology as a standard Java extension.
JSP soon followed, with the first draft API specifications appearing in 1998. 7
JSP History
JSP 1.0 Specification was released in June 1999 as a part of J2EE.
JSP 1.1 - Late 1999.
JSP 1.2 - 2001.
JSP 2.0 – 2003. 8
Third party vendor support RAD tools are now available to create dynamic web pages, using DnD approach.
Ability to create sophisticated JSP pages without seeing HTML tags, let alone Java code will enhance the productivity to a greater extent.
Ex: Drumbeat 2000 from Macromedia IBM’s Visual Age for Java HomeSite from Allaire
9
JSP vs ASP Features Asp
Jsp
WEB Server
IIS, PWS
Many
Platform
Windows Any
Reusable components
Com
Javabeans/EJB
Memory leak protection Scripting languages
No
Yes
Security
J-script, Java VB-script No yes
Customized tags
No
yes 10
JSP vs JavaScriptJavaScript
Validates on Client Side
Browser Dependent
Unstable
Interpreted
Server-side JavaScript is dependent on proprietary servers. 11
JSP vs Servlets
Similarities
Provides identical results to end user.
JSP is an extension of servlets.
Provides similar API support. 12
JSP vs Servlets
Differences
Servlets: “HTML embedded in Java Code” HTML code inaccessible to Graphics designer But accessible to Programmer.
JSP: “Java Code embedded in HTML” HTML code accessible to Graphic Designer Java code accessible to Programmer.
Jsp allows code update without restarting the server.
Eliminates redundant code.
13
Comparing servlet and JSP code
1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*;
5. public class HelloWorld extends HttpServlet 6. { 7. public void doGet(HttpServletRequest req, HttpServletResponse res) 8. throws ServletException, IOException 9. { 10. res.setContentType("text/html"); 11. PrintWriter out = res.getWriter(); 12. out.println(""); 13. out.println("<TITLE>Hello World"); 14. out.println(""); 15. out.println("
Hello World"); 16. out.println(""); 17. } 18. } 14
Comparing servlet and JSP code 1. 2. <TITLE>Hello World 3. 4.
Hello World 5. 6.
Note: HTML content is also valid JSP content, since JSP is HTML code embedded with java code. 15
JSP functionality architecture Web Server JSP Page est u q Re
Translation by JSP engine Generated Servlet
Web Client
Compilation Re
sp
on
se
Compiled Servlet Instantiation Servlet is loaded to server 16
JSP functionality architecture
17
JSP life cycle
jspInit() jspDestroy() _jspService( request, response ) jspInit() Initialise JSP Invoked only once
_jspService(request,response) Handle Requests: invoked for every request
jspDestroy() Invoked by container to cleanup
•Implementation of these methods are generated by the Container and not by JSP authors. 18
JSP and the JSP Engine Contract between the JSP engine and JSP
jspInit() Corresponds to servlet init(), but has no parameters (use config implicit object to obtain information regarding environment).
jspService() The main processing method; all Java code belongs to this method by default (if not contained in another method), but it is not explicitly declared in a JSP document.
jspDestroy() Corresponds to the servlet destroy() method and is called just before the generated servlet is destroyed. 19
Package java.servlet.jsp Interface Hierarchy
Class Hierarchy 20
Interface javax.servlet.Servlet
•Top most in the servlet API hierarchy. •It is implemented by javax.servlet.GenericServlet, which is further extended by javax.servlet.http.HttpServlet. •public void init(ServletConfig config) •public void service( ServletRequest req, ServletResponse res) •public void destroy() •public ServletConfig getServletConfig() •public String getServletInfo()
21
Interface JspPage It describes the generic interaction that a JSP
Page implementation class must satisfy. Pages that use HTTP protocol are described by HttpJspPage interface.
public void jspInit() Invoked when the JSP page is initialized. public void jspDestroy() Invoked before destroying the JSP page.
Note: The jspInit() and jspDestroy() can be defined by a JSP author, but _jspService() is defined automatically by the JSP processor based on contents of the JSP page. 22
Interface HttpJspPage Extends JspPage and describes interaction
that a JSP Page implementation class must satisfy when using HTTP protocol. Behaviour is identical to JspPage, except that _jspService method is now expressible in Java type system optimized for HTTP.
void _jspService( HttpServletRequest request, HttpServletResponse response) It corresponds to body of the JSP page. It is defined automatically by the JSP container.
23
Class JspFactory
Defines factory methods available to a JSP page at runtime to enable instantiation of implementation-dependent PageContext and JspEngineInfo that support JSP implementation. JSP Engine, during it's startup instantiates an implementation dependent subclass of this class. This instance is made globally available by registering it using setDefaultFactory() method. Note: JspFactory objects should not be used by JSP page authors. 24
Class JspFactory
static static abstract abstract
void setDefaultFactory(JspFactory deflt) JspFactory getDefaultFactory() JspEngineInfo getEngineInfo() PageContext getPageContext( Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int buffer, boolean autoflush) Instantiates an implementation dependent PageContext for the calling Servlet. abstract void releasePageContext(PageContext pc)25
Class JspEngineInfo
Provides information about the current JSP engine (container).
abstract String getSpecificationVersion() Return version of the JSP specification supported by this JSP engine. May return null, if version details is not known. 26
Class PageContext
Provides access to JSP implicit objects and page attributes.
It is an abstract class, and is implemented by container provider.
It is instantiated using static method getPageContext() and is released using releasePageContext() of JspFactory. 27
Field Summary
static String APPLICATION Name used to store ServletContext in PageContext name table. static String CONFIG Name used to store ServletConfig. static String EXCEPTION Name used for uncaught exception. static String OUT Name used to store current JspWriter. static String PAGE Name used to store the Servlet. static String PAGECONTEXT 28 Name used to store this PageContext.
Field Summary…
static String REQUEST Name used to store ServletRequest. static String RESPONSE Name used to store ServletResponse. static String SESSION Name used to store HttpSession.
static int PAGE_SCOPE static int REQUEST_SCOPE static int SESSION_SCOPE static int APPLICATION_SCOPE
Indicates scope of a bean reference. 29
Method Summary The following methods provide convenient
access to implicit objects: abstract JspWriter getOut() Returns current value of the out object (JspWriter). abstract Object getPage() abstract ServletRequest getRequest() abstract ServletResponse getResponse() abstract ServletConfig getServletConfig() abstract ServletContext getServletContext() abstract HttpSession getSession() abstract Exception getException() 30
Method Summary Object findAttribute( String name)
Search and return attribute value (or null) in scope sequence of page, request, session and application. Object getAttribute( String name) Return attribute value of name in page scope. Enumeration getAttributeNamesInScope(int scope) abstract int getAttributesScope( String name) void removeAttribute( String name) Search for attribute in scope order and remove it. void removeAttribute( String name, int scope) void setAttribute( String name, Object value) Register attribute in page scope. void setAttribute( String name, Object v, int scope) 31
Method Summary abstract void forward( String relativeUrlPath)
Re-directs/forwards current Request and Response to another component. abstract void include( String relativeUrlPath) Inserts content/output of refered component. abstract void handlePageException ( Exception e) Redirects exception to the specified error page (if available) or to default handler. abstract void handlePageException ( Throwable t ) 32
Method Summary abstract void initialize(Servlet ser,
ServletRequest req, ServletResponse res, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) Initializes PageContext to be used by a JSP to service an incoming request. abstract void release() It resets PageContext state, releasing internal
references and preparing PageContext for reuse by a later invocation of initialize().
33
Method Summary
Following methods enable management of JspWriter streams to implement Tag Extensions:
JspWriter popBody()
Returns JspWriter saved by the matching pushBody(), and updates value of "out“ attribute in page scope of the PageConxtext.
BodyContent pushBody()
Returns a new BodyContent object, and updates the value of "out“ attribute in the page scope attribute namespace of the PageContext. 34
Class JspWriter
Provides output stream for JSP's. It extends java.io.Writer. A JSPWriter object is available within JSP as implicit object out, which is initialized automatically using methods of PageContext object. abstract abstract abstract
abstract
abstract
void void void int int boolean void
clearBuffer() close() flush() getBufferSize() getRemaining() isAutoFlush() newLine()
35
Class JspWriter… void println() void print(boolean b) void print(char c) void print(char[] s) void print(double d) void print(float f) void print(int i) void print(long l) void print(Object obj) void print(String s)
void void void void void void void void void
println(boolean x) println(char x) println(char[] x) println(double x) println(float x) println(int x) println(long x) println(Object x) println(String x)
36
Tag convention JSP tags usage is similar to those of HTML tags: They begin and end with angle brackets.
JSP tags fall into 2 basic categories: Scripting-oriented tags inspired by ASP. Tags based on XML style. 37
ASP-like Tags
They can be recognized by their delimiters. They start with <% and end with %>. Additional character may appear after the initial <%, such as !, =, or @, to further specify the meaning of the tag. Example: <%! double radius = 7.5; %> <%= 2 * Math.PI * radius %> <% if (radius > 10.0) { out.println("Exceeds recommended maximum"); } %> <%@ include file="copyright.html" %> 38
ASP-like Tags…
NOTE : All ASP-scripting like tags are self-contained. All the information relevant to the tag, and all of the data it will act on, is contained within the individual tags themselves. None of these scripting-oriented JSP tags have bodies. 39
XML-like tags
They start with < and not <% Tag names have an embedded colon. They are similar to HTML tags; They can have a "start tag", a "tag body" and an "end tag". XML syntax is similar to HTML, but adds a few rules to avoid certain problems. XML tags are case sensitive ( and <TITLE> are treated as two different tags). All attribute values must be quoted (In HTML, quotes are optional). All XML tags must also have a delimiting tag. 40
Example 1. <jsp:forward page="admin.jsp"/> 2. <jsp:useBean id="login“
class="UserBean"> <jsp:setProperty name="login“ property="group“ value="admin"/> 41
Components of a JSP program • HTML code • Comments • JSP tags • JSP Implicit Objects • Java Beans 42
Comments in JSP
1. Plain HTML Comments Ex: Response:
2. HTML Comments containing JSP tags Ex: < !-- value of 10 + 20 is <%= 10 + 20 %> --> Response: 3. JSP Comment tag Ex: <%-- This is a JSP comment --%> Response: 4. Java Comments Ex: <%
%>
/* int x; float f; */ void meth1() { //out.println( “hello output” ); } 43
JSP tag types
•Declaration tags •For variable and method declaration •Format: <%! Variable declaration; Method declaration; %> •Expression tags •For inserting Java expressions •format: <%= expression %> •Scriptlets •To embed java code blocks •format: <% code block %>
44
JSP tag types… •Directives
• To specify information that affect the whole JSP program • format: <%@ directive_type directive_attribute %> •Action tags •Used to work with standard objects •format: <jsp:action_name action_attributes /> or <jsp:action_name action_attributes> … 45
General rules JSP tags are case sensitive
Tags may have attributes
Attribute values must always appear quoted
White space with in the JSP page is not significant
The \ character can be used as an escape sequence
46
Sample Program -1
•Using simple expression tag My first JSP program
The Current system date is : <%= new java.util.Date() %>
47
Deploying JSP’s on TOMCAT
48
Deploying JSP’s on J2EE RI Server
49
Deploying JSP’s on Weblogic
50
Deploying JSP’s on JRun
51
Sample Program - 2
•Hello word example <%
String name = null; name = request.getParameter(“name”); if ( name == null ) { %> Hello, World <% } else { out.println(“Hello ” + name); } %>
52
Sample Program - 3
Java Version : <%= System.getProperty( "java.version" ) %>
Java Home : <%= System.getProperty( "java.home" ) %>
Os Name : <%= System.getProperty( "os.name" ) %>
User Name : <%= System.getProperty( "user.name" ) %>
User Home : <%= System.getProperty( "user.home" ) %>
User Directory : <%= System.getProperty( "user.dir" ) %>
53
Sample Program 4 •Simple usage of page directive, scriptlet and expression tags. <%@ page import="java.util.*" %> <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now <%= date %> 54
Sample Program - 5
•Using page directive, declaration tag and expression tags together. <%@ page import="java.util.*" %> <%! Date dateobj = new Date(); Date getDate() { System.out.println( "In getDate() method" ); return dateobj; } %> Hello! The time is now <%= getDate() %>
55
Note about declaration tags Declarations in Declaration tag will become instance members. Variables in Declaration tags will be evaluated only once, during translation of the JSP page. Its behavior is same as definition of instance variables in a class. Hence it will not have different functionality for different clients. Client specific data must not be put in declaration tags, since they are shared. Sessions can be used for the purpose. 56
Control statements in JSP Sample Program - 6 •Using if condition statements <%! boolean validate_data( String value ) { if( value.trim().equals( "xyz" ) ) return true; else return false; } %> <% if( validate_data( "hello" ) ) { %> Welcome, the data is valid
<% }else{ out.println( " invalid data, try again
" ); } %> 57
Control statements in JSP
Sample Program 7 •Using for loops
<%! String items[] = { "bread", "rice", "dal" }; int quantity[] = { 2, 5, 3 }; double cost[] = { 12.50, 19.50, 28.75 }; %>
ITEM | QUANTITY | PRICE |
<% for( int i =0; i < items.length; i++ ) { %> <%= items[ i ] %> | <%= quantity[ i ] %> | <%= quantity[ i ] * cost[ i ] %> |
<% } %>
58
Control statements in JSP
Sample Program - 8
•Another example of using for loops
<% String color_arr[] = { "00", "11", "22", "33", "44", "55", "66", "77", "88", "99", "AA", "BB", "CC", "DD", "EE", "FF" }; for(int i = 0; i < 5; i++ ) { String col = color_arr[ i * 3 ] + color_arr[ i * 3 ] + color_arr[ i * 3]; %> > > Welcome to Step India > <% }
%>
59
Built-in/Implicit JSP Objects •Besides objects explicitly created by a developer within JSP scripting elements, the JSP container provides a few internal objects, referred to as implicit objects. •The developer may assume that these objects will be automatically assigned to specific variable names. •They work as a shorthand for certain class/interface instances of Servlet/JSP API. •These Objects are available for ready usage. 60
JSP Objects description JSP object Servlet API Object
Description
application
javax.servlet.ServletContext Context (Execution environment) of the Servlet.
config
javax.servlet.ServletConfig
The ServletConfig for the JSP.
exception
java.lang.Throwable
The exception that resulted when an error occurred.
out
javax.servlet.jsp.JspWriter
An object that writes into a JSP's output stream. 61
JSP Objects description… JSP object Servlet API Object pageContext javax.servlet.jsp.PageContext
Description Page context for the JSP.
request
javax.servlet.HttpServletRequest The client request.
response
javax.servlet.HttpServletResponse
The response to the client.
session
javax.servlet.http.HttpSession
Session object created for requesting client.
page
javax.servlet.Servlet
Refers to current servlet object. 62
request object
•It provides access to data sent within a HTTP Request. Cookie[] Enumeration String String HttpSession HttpSession
getCookies() getHeaderNames() getQueryString() getRemoteUser() getSession() getSession(boolean create)
String boolean
getRequestedSessionId() isRequestedSessionIdValid()
Enumeration int String boolean boolean StringBuffer String String String
getHeaderNames() getIntHeader(java.lang.String name) getHeader(String name) isRequestedSessionIdFromCookie() isRequestedSessionIdFromURL() getRequestURL() getServletPath() getMethod() getContextPath()
63
Sample Program - 9 <%@ page language="java" contentType="text/html" %> The following information was received :
- Request Method : <%= request.getMethod() %>
- Request URI : <%= request.getRequestURI() %>
- Request Protocol : <%= request.getProtocol() %>
- Request Servlet Path : <%= request.getServletPath() %>
- Request Query String : <%= request.getQueryString() %>
- Request Sever Name : <%= request.getServerName() %>
- Request Port : <%= request.getServerPort() %>
- Request Address : <%= request.getRemoteAddr() %>
- Request Browser : <%= request.getHeader("User-Agent") %>
64
response object
•It allows setting of response message including html Code, cookies, headers and other information. void void void void void boolean void String String void void
addCookie(Cookie cookie) addHeader( String name, String value) addIntHeader( String name, int value) setHeader( String name, String value) setIntHeader( String name, int value) containsHeader( String name) sendRedirect( String location) encodeRedirectURL(String url) encodeURL(String url) setStatus(int sc) setStatus(int sc, String sm) 65
Sample Program - 10
<% Cookie cookies[] = request.getCookies(); boolean flag = false; String name; try{ for( int i = 0; i < cookies.length; i++ ) { name = cookies[ i ] .getName(); out.println( name + " : " + cookies[ i ].getValue( ) + "
" ); if( name.trim().equals( "user_id" ) ) flag = true; } }catch( Exception e ){ System.out.println( e ); } if( ! flag ) { out.println( "No cookies found" ); response.addCookie( new Cookie( "user_id", "STEP" ) ); } %> 66
session object •It stores information for a particular user session. •Data stored in a session object are not discarded when the user jumps between pages in the application; they persist for the entire user session. •The web server destroys the session object when the session is invalidated. Object void Enumeration void void Object String[] void
getAttribute( String name) setAttribute( String name, Object value) getAttributeNames() removeAttribute( String name) putValue( String name, Object value) getValue( String name) getValueNames() removeValue( String name) 67
session object (Contd) String long long int void interval) ServletContext HttpSessionContext void boolean
getId() getCreationTime() getLastAccessedTime() getMaxInactiveInterval() setMaxInactiveInterval(int getServletContext() getSessionContext() invalidate() isNew() 68
Sample Program - 11
<%
java.util.Enumeration attribute_names = session.getAttributeNames(); String attr_name, attr_value; boolean entires_found_flag = false; if( attribute_names != null ) { while( attribute_names.hasMoreElements() ) { entires_found_flag = true; attr_name = (String) attribute_names.nextElement(); attr_value = (String) session.getAttribute( attr_name.trim() ); out.println( "value of the attribute " + attr_name + " is " + attr_value + "
" ); } } if( entires_found_flag == false ) { session.setAttribute( "attribute1", "value1" ); session.setAttribute( "attribute2", "value2" ); } %> 69
Sample Program - 12
<% String name = request.getParameter( "username" ); session.setAttribute( "theName", name ); %>
Continue
Hello, <%= session.getAttribute( "theName" ) %>
B.jsp
C.jsp 70
application object
•Allows interaction with Servlet container/environment. Object getAttribute(String name) Enumeration getAttributeNames() void removeAttribute( String name) void setAttribute(java.lang.String name, Object object) String getInitParameter(String name) Enumeration getInitParameterNames() String getServerInfo() int getMajorVersion() int getMinorVersion() String getMimeType( String file ) java.lang.String getRealPath(java.lang.String path) Servlet getServlet(java.lang.String name) Enumeration getServletNames() Enumeration getServlets() void log( Exception exception, String msg) void log( String msg) void log( String message, Throwable throwable) String getServletContextName() RequestDispatcher getRequestDispatcher(java.lang.String path) 71
Sample Program - 12
Display the default application settings
<% out.println( application.getServerInfo() + "
" ); java.util.Enumeration enum = application.getAttributeNames(); String element_name; while( enum.hasMoreElements() ) { element_name = (String) enum.nextElement(); out.println( "
" + element_name + " ----------------" + application.getAttribute( element_name ) + "
"); } %> 72
config object
It passes configuration information to a servlet when it is instantiated. The information includes initialization parameters and the ServletContext object, which describes the context within which the servlet is running.
String Enumeration String ServletContext
getInitParameter(String name) getInitParameterNames() getServletName() getServletConext()
73
Sample Program - 13 <% java.util.Enumeration params = config.getInitParameterNames(); String name; out.println( "
" ); while( params.hasMoreElements() ) { name = (String) params.nextElement(); out.println( "- " + name + "..." + config.getInitParameter( name.trim() )+ "
" ); } out.println( "
" ); %>
74
exception object
•It represents all errors and exceptions. It can be accessed in a JSP page that is declared as an error page using the isErrorPage attribute of the page directive. String getMessage() String printStackTrace() String toString()
75
out object
It defines an object for writing to JSP's output stream. void void int int boolean void
clearBuffer() flush() getBufferSize() getRemaining() isAutoFlush() newLine()
void void
print(...) println(...)
76
pagecontext object
•It stores information local to a JSP. •Each JSP has its own pageContext object that the server creates when the user accesses the page •It is deallocated when the user leaves the page. Object void void JspWriter Object ServletRequest ServletResponse ServletConfig ServletContext HttpSession Exception void void
findAttribute(String name) removeAttribute(String name) setAttribute(String name, Object attribute) getOut() getPage() getRequest() getResponse() getServletConfig() getServletContext() getSession() getException() forward(String path ) include( String path)
77
Sample Code <% Object val = pageContext.findAttribute( pageContext.PAGE ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.APPLICATION ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.CONFIG ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.EXCEPTION ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.OUT ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.PAGECONTEXT ); out.println( val + "
" ); %> 78
JSP Standard Action Tags (XML format)
•They replace large sections of Java code. •Standard actions are actions that must be implemented by every JSP container. •They perform actions such as instantiating an object or changing an objects state. •JSP actions are a technique to separate business logic from presentation logic (removes Java code from JSP). •In reality, actions does not remove Java code but hides Java code from JSP author.79
JSP Action tags (Contd)
Standard action tags start with the namespace prefix jsp followed by a colon and then by tag name.
Ex: <jsp:param>
Actions may have attributes and tag bodies.
80
Handling of Actions
JSP translators treat action tags as tokens that must be replaced with Java code.
Code for actions are defined in a tag library.
The translator simply replaces action tags with output of the code that is referenced by the action.
81
Handling of Actions…
Ex: The tag
<jsp:useBean id=“test” class=“one.two.Tester”>
will be replaced with Object test = (one.two.Tester) java.beans.Beans.instantiate( this.getClass().getClassLoader(), “one.two.Tester” );
82
Action tags Following action tags are available: <jsp:useBean> <jsp:getProperty>
<jsp:setProperty>
<jsp:param> <jsp:forward>
<jsp:include> <jsp:plugin> 83
useBean action tag
•It is used to access a Java bean (not EJB) in a JSP document. •Causes container to find an existing instance of the bean in the scope, with the specified id. If object is not found in that scope, container tries to create a new instance. •The setProperty and getProperty action tags are related to this tag. Syntax: <jsp:useBean attribute_name=attribute_value /> 84
Attributes in useBean tag Attribute
Function
id
Name used to refer the bean within the page. Must be unique.
scope
page/request/session/application.
class
Fully qualified bean class name.
beanName Bean name as per bean spec. type
Reference type (super class or same type). 85
Attributes in useBean tag Possible combination of attributes in
Possible combination of attributes in useBean tag:
class Creates an instance of given class class, type Creates an instance of given class; the bean will have the given type. beanName, type Creates an instance of given bean, bean will have the given type. type if an object of the given type exists in the session, the id will refer that object. 86
setProperty action tag •It allows to set/assign a value for a bean property. •Bean id must be created using useBean tag before using setProperty and getProperty tags. •Syntax: <jsp:setProperty attr_name=attri_val /> Attributes: name property param value 87
Attributes in setProperty tag Attribute Description name Bean id specified in useBean. property Name of the property to be set. If individual bean property is specified, respective setter method will be invoked. If *, client request parameter with same name as bean property will be used to set the values. param Client request parameter whose value will be used to set the value. value Value to be assigned to the property. 88
Attributes in setProperty tag
The name and property attributes are mandatory.
param and value attributes are mutually exclusive.
If param and value are not used, the tag attempts to use value of the request parameter with same name. 89
getProperty action tag •It allows to retrieve the value of a bean property. •Syntax: <jsp:getProperty attr_name=attri_val /> Attributes: name->bean id specified in useBean. property-> property whose value is to retrieved. 90
package test;
Bean access code 1 (bean)
public class StudentBean { private int id; private String name; public StudentBean() { id = -1; name = "---"; } public int getId() public void setId( int student_id ) public String getName() public void setName( String n )
test/StudentBean.java
{ { { {
return id; id = student_id; } return name; } name = n;
} }
} 91
Bean access code 1 (JSP) <jsp:useBean id="stBean" class="test.StudentBean" scope="page" /> Details Before changing the bean
Student id : <jsp:getProperty name="stBean" property="id" />
Student name : <jsp:getProperty name="stBean" property="name" />
<jsp:setProperty name="stBean" property="id" value="101" /> <jsp:setProperty name="stBean" property="name" value="step_student" /> Details After changing the bean
Student id : <jsp:getProperty name="stBean" property="id" />
Student name : <jsp:getProperty name="stBean" property="name" /> 92
Beans and Form processing package test2; public class UserData { String username; String email; int age;
UserData.java
public void setUsername( String value ){ public void setEmail( String value ){ public void setAge( int value ){
username = value; email = value;
age = value;
}
}
}
public String getUsername() { return username; } public String getEmail() { return email; } }
public int getAge() { return age; } 93
Beans and Form processing
<jsp:useBean id="user" class="test2.UserData" scope="session"/> <jsp:setProperty name="user" property="*"/>
Continue
<jsp:useBean id="user" class="test2.UserData" scope="session"/> The following data were received by the client
Name: <%= user.getUsername() %>
Email: <%= user.getEmail() %>
Age: <%= user.getAge() %>
beantest.jsp
result.jsp
94
Another Example package test3; public class User { private String id; private String surname;
}
public void setId( String id ){ this.id = id;} public String getId(){ return id; } public void setSurname( String surname ) { this.surname = surname; } public String getSurname( ){ return surname; } 95
Another Example <jsp:useBean id="userA" class="test3.User" /> <jsp:setProperty name="userA" property="surname" value="Smith" /> <jsp:setProperty name="userA" property="id" value="<%= 32 + 45 + "45" %>" /> Your data are as follows :
ID : <jsp:getProperty name="userA" property="id" />
SURNAME : <jsp:getProperty name="userA" property="surname" />
96
include action tag • It allows embedding of another page within the current jsp. • Included components must be valid JSP pages or servlets. • Note: Included file is not allowed to modify response headers, nor to set cookies in the response. • Syntax: <jsp:include page->file (Mandatory) flush->true/false (Optional)
97
How include action works
1.
2.
3.
Original JSP file stops processing and passes the request to included file. The included file generates its response. Response of the included file is returned to the calling JSP, which proceeds with its processing and generates the final response. 98
Sample Code <TITLE>Example Of The include Action Include the First File <jsp:include page="test1.jsp" />
Include the Second File: <jsp:include page="test2.jsp" />
99
forward action tag • It is used to transfer the control to another JSP, HTML or servlet. • It permanently transfers processing from one JSP to another on the local server. • Any content generated by the original page is discarded and processing begins anew at the second JSP. • Syntax: <jsp:forward page->url />
100
How forward action works Original JSP file stops processing and passes the request to forwarded component. Forwarded component generates the final response. Note:
Execution never returns to the calling page. Only one effective forward action is valid in a JSP document, later forward actions are ignored. 101
Sample Code <TITLE>Example Of The forward Action <% if (Math.random() > .5) { %> <jsp:forward page=“one.jsp" /> <% } else { %> <jsp:forward page="two.jsp" /> <% } %> <%= System.getProperties() %> 102
param action tag
• It is used in conjunction (as a sub-tag) with include or forward action. • It is used to pass parameters to the resource being included/forwarded. • In the included/forwarded resource these parameters can be accessed using getParameter() method. • Syntax: <jsp:include …..> <jsp:param name->name value->value > . .
103
plugin action tag • It is used to embed objects for execution on client • It is similar to