SlideShare a Scribd company logo
Java Server Pages Java server pages is a technology for developing portable java web applications that runs on a java web server. Main motivation behind developing JSP was to develop a technology so that a non-java programmer or a person with little knowledge of java could write web applications for java plaform. Initially JSP was developed to replace servlet but now common practice is to use servlet and jsp together using MVC(model-view-controller) pattern. JSP allows developer to write html (static content),jsp action tags and  java (dynamic content) code in the same page. JSPs are compiled into java servlets by a jsp compiler, thus internally jsp page is converted into servlet, it is must to understand java servlet technology throughly for becoming a good jsp programmer.
Java Server Pages JSP enables you to separate the dynamic content of a web page from its presentation. It caters to different types of developes. Web designers, who are responsible for the graphical design of the page Java developers, who write the code to generate dynamic content.
JSP Life Cycle JSP life cycle includes following steps/phases: JSP page translation – generate servlet source code The translation occurs only when jsp page has to serve its first request. Translation does not have to happen again unless the page is updated. JSP page compilation – compile generated code into byte code Load class Create instance  Call the jspInit method Call the _jspService method - for each request Call the jspDestroy method
Deploying JSP User don’t need to register jsp pages in deployment descriptor file web.xml. Just place them in the accessible area of a web application directory structure and user can access them. How ever you can register a jsp page same way as a servlet. You even use the <servlet> element with one vital difference – where the <servlet-class> would apper,you substitute <jsp-file> instead. <servlet> <servlet-name>JspName1<servlet-name> <jsp-file>/instanceCheck.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>JspName1</servlet-name> <url-pattern>/jspName2</url-pattern> </servlet-mapping>
Deploying JSP Now you can access jsp page in following two ways http://localhost:8080/myapp/instanceCheck.jsp OR http://localhost:8080/myapp/jspName2 if you want to supress direct access to jsp , locate jsp page under  WEB-INF directory.
 
JSP API Translated JSP Servlet implements javax.serlvet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage. The javax.servlet.jsp.JspPage interface contains two methods:  1. public void jspInit() - This method is invoked when the JSP is initialized and the page authors are free to provide initialization of the JSP by implementing this method in their JSPs.  2. public void jspDestroy() - This method is invoked when the JSP is about to be destroyed by the container. Similar to above, page authors can provide their own implementation.  The javax.servlet.jsp.HttpJspPage interface contains one method:  public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  This method generated by the JSP container is invoked, every time a request comes to the JSP. The request is processed and the JSP generates appropriate response. This response is taken by the container and passed back to the client.
Java Server Pages JSP Elements Directives Scripting Elements JSP Actions Templates
JSP Scripting Elements There are four types of scripting elements defined Declaration Expression Scriptlets Comments
Declaration Declares a variable or method valid in the scripting language used in the JSP page.  JSP Syntax <%! declaration; [ declaration; ]+ ... %>  XML Syntax  <jsp:declaration>      code fragment  [ declaration; ]+ ... </jsp:declaration> Examples <%! int i = 0; %>  <%! int a, b, c; %>  <%! Circle a = new Circle(2.0); %>
Declaration A declaration declares one or more variables or methods that you can use in Java  code later in the JSP page. You must declare the variable or method  before  you use it in the JSP page.  You can declare any number of variables or methods within one declaration element, as long as you end each declaration with a semicolon. The declaration must be valid in the Java programming language.  You can use declaration to write anything that would be placed in the generated servlet outside of the _jspService method.  You can place in your declaration any code that can appear in  a servlet soure file; instance methods, static methods, inner classes . You can also use declarations to override some methods that appear further up in the jsp servlet hierarchy – namely jspInit and jspDestroy.
Expression Contains an expression valid in the scripting language used in the JSP page.  JSP Syntax <%=  expression  %>  XML Syntax <jsp:expression>     expression  </jsp:expression> Description An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted into the response where the expression appears in the JSP page. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP page.  Example Welcome, <%=userName%> Output: Welcome, James
Expression <%= new java.util.Date()%> When this is generated into servlet code, the resulting java stmt will probably look like this: out.print(new java.util.Date()); Out is an instance of javax.servlet.http.jsp.JspWriter and it is associated with the response for the generated servlet. Cotents of your jsp expression are used directly as the parameter to the print() method.so it must not end with semicolon.
Script lets Contains a code fragment valid in the page scripting language.  Scriptlets allows you to include a series of java statements inside the _jspService method that are executed on every request to the page.these java stmts are incorporated into _jspService method as it is.so you must terminate them with semicolon. JSP Syntax <%  code fragment  %>  OR  <jsp:scriptlet>     code fragment  </jsp:scriptlet>
Scriptlets Examples <%   String name = null;      if (request.getParameter(&quot;name&quot;) == null) { %>   <%@ include file=&quot;error.html&quot; %>  <%   }    else {     userObject.setName(request.getParameter(&quot;name&quot;));     } %>
Comments To denote any lines you want to be completely ignored by the JSP translation process. Example <%-- Author: James Gosling --%>
JSP Directives Directives are instructions to jsp compiler. Those intructions tell the compiler that some action needs to be taken. General syntax for directives is: <%@ Directive-name attribute-value pairs %> There are three main directives defined in jsp Page Include Taglib
Page Directive Page Directive- Defines attributes that apply to an entire JSP page. JSP Syntax <%@ page  language=&quot; java &quot;  import=&quot;{ package.class  |  package.* }, ...&quot;    ,    session=&quot; true |false&quot;  %>  OR  <jsp:directive.page pageDirectiveAttrList /> where  pageDirectiveAttrList  is the same as the list in the JSP syntax.  XML Syntax <jsp:directive.page pageDirectiveAttrList /> where  pageDirectiveAttrList  is the same as the list in the JSP syntax.  Examples <%@ page import=&quot;java.util.*, java.lang.*&quot; %>   <%@ page buffer=&quot;5kb&quot; autoFlush=&quot;false&quot; %> <jsp:directive.page errorPage=&quot;error.jsp&quot; />
Page Directive Description The page directive applies to an entire JSP page and any of its  static include files , which together are called a  translation unit . A static include file is a file whose content becomes part of the calling JSP page. The page directive does not apply to any dynamic resources; see  < jsp:include >  for more information.  You can use the page directive more than once in a translation unit, but you can only use each attribute, except import, once. Because the import attribute is similar to the import statement in the Java programming language, you can use a page directive with import more than once in a JSP page or translation unit.  No matter where you position the page directive in a JSP page or included files, it applies to the entire translation unit. However, it is often good programming style to place it at the top of the JSP page.
Page Directive Attributes language=&quot; java &quot;  The scripting language used in scriptlets, declarations, and expressions in the JSP page and any included files. In v2.0, the only allowed value is java.  extends=&quot; package.class &quot;  The fully qualified name of the superclass of the Java class this JSP page will be compiled to. Use this attribute cautiously, as it can limit the JSP container's ability to provide a specialized superclass that improves the quality of the compiled class.
Page Directive import=&quot;{ package.class  |  package.* }, ...&quot;  A comma-separated list of Java packages that the JSP page should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP page. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP page.  The following packages are implicitly imported, so you don't need to specify them with the import attribute:  java.lang.*  javax.servlet.*  javax.servlet.jsp.*  javax.servlet.http.*  You must place the import attribute before the element that calls the imported class.
Page Directive isThreadSafe=&quot; true |false&quot;  Whether thread safety is implemented in the JSP page. The default value is true, which means that the JSP container can send multiple, concurrent client requests to the JSP page. You must write code in the JSP page to synchronize the multiple client threads. If you use false, the JSP container sends client requests one at a time to the JSP page.  info=&quot; text &quot;  A text string that is incorporated verbatim into the compiled JSP page. You can later retrieve the string with the Servlet.getServletInfo() method.  errorPage=&quot; relativeURL &quot;  A pathname to a JSP page that this JSP page sends exceptions to. If the pathname begins with a /, the path is relative to the JSP application's document root directory and is resolved by the web server. If not, the pathname is relative to the current JSP page.
Page Directive isErrorPage=&quot;true| false &quot;  Whether the JSP page displays an error page. If set to true, you can use the exception object in the JSP page. If set to false (the default value), you cannot use the exception object in the JSP page.  contentType=&quot; mimeType  [; charset= characterSet  ]&quot; |      &quot; text/html;charset=ISO-8859-1 &quot;  The MIME type and character encoding the JSP page uses for the response. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.  pageEncoding=&quot; characterSet  |  ISO-8859-1 &quot;  The character encoding the JSP page uses for the response. The default character set is ISO-8859-1.
Include Directive Includes a static file in a JSP page, parsing the file's JSP elements.  JSP Syntax <%@ include file=&quot; relativeURL &quot; %> OR  <jsp:directive.include file=&quot; relativeURL &quot; />  XML Syntax <jsp:directive.include file=&quot; relativeURL &quot; /> Examples include.jsp:  <html>  <head> <title>An Include Test</title> </head> <body bgcolor=&quot;white&quot;> <font color=&quot;blue&quot;>  The current date and time are <%@ include file=&quot;date.jsp&quot; %>  </font> </body> </html>
Include Directive date.jsp <%@ page import=&quot;java.util.*&quot; %>  <%= (new java.util.Date() ).toLocaleString() %> Displays in the page: The current date and time are Aug 30, 1999 2:38:40  Description An include directive inserts a file of text or code in a JSP page at translation time, when the JSP page is compiled. When you use the include directive, the include process is  static . A static include means that the text of the included file is added to the JSP page. The included file can be a JSP page, HTML file, XML document, or text file. If the included file is a JSP page, its JSP elements are translated and included (along with any other text) in the JSP page. Once the included file is translated and included, the translation process resumes with the next line of the including JSP page.
Include Directive Attributes file=&quot; relativeURL &quot;  The pathname to the included file, which is always a relative URL. A relative URL is just the path segment of an URL, without a protocol, port, or domain name, like this:  &quot;error.jsp&quot; &quot;/templates/onlinestore.html&quot; &quot;/beans/calendar.jsp&quot;  If the relative URL starts with /, the path is relative to the JSP application's context, which is a javax.servlet.ServletContext object that is in turn stored in the application object. If the relative URL starts with a directory or file name, the path is relative to the JSP page.
taglib directive Defines a tag library and prefix for the custom tags used in the JSP page.  JSP Syntax <%@ taglib {uri=&quot; URI &quot; | tagdir=&quot;/WEB-INF/tags[/ subdir ]+&quot;} prefix=&quot; tagPrefix &quot; %>  Examples <%@ taglib uri=&quot;http://www.jspcentral.com/tags&quot; prefix=&quot;public&quot; %>  <public:loop>    ... </public:loop>  Description The taglib directive declares that the JSP page uses custom tags, names the tag library that defines them, and specifies their tag prefix.  You must use a taglib directive  before  you use the custom tag in a JSP page. You can use more than one taglib directive in a JSP page, but the prefix defined in each must be unique.
taglib Directive Attributes uri =&quot; URI &quot;- The Uniform Resource Identifier (URI) that uniquely locates the TLD that describes the set of custom tags associated with the named tag prefix. Prefix =‘tagprefix’ The prefix that precedes the custom tag name, for example, public in <public:loop>. Empty prefixes are illegal. If you are developing or using custom tags, you cannot use the tag prefixes jsp, jspx, java, javax, servlet, sun, and sunw, as they are reserved by Sun Microsystems.
JSP ACTIONS Servlet container provides many built in functionality to ease the development of the applications Programmers   can use these functions in JSP applications. The JSP Actions tags enables the programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page.  Here is the list of JSP Actions: jsp:include  The  jsp:include  action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page.    jsp:param   The  jsp:param  action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block.   jsp:forward   The  jsp:forward  tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page.   
JSP ACTIONS jsp:getProperty  The  jsp:getPropertyB  is used to get specified property from the JavaBean object.     jsp:setProperty   The  jsp:setProperty  tag is used to set a property in the JavaBean object.     jsp:useBean   The  jsp:useBean   tag is used to instantiate an object of Java Bean or it can re-use existing java bean object.
Simple JSP Example <%@page contentType=&quot;text/html&quot; import=&quot;java.util.*&quot; %>   <html> <body> <p>&nbsp;</p><div align=&quot;center&quot;><center> <table border=&quot;0&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; width=&quot;460&quot; bgcolor=&quot;#EEFFCA&quot;> <tr> <td width=&quot;100%&quot;><font size=&quot;6&quot; color =&quot;#008000&quot;>&nbsp;Date Example</font></td> </tr> <tr><td width=&quot;100%&quot;><b>&nbsp;Current Date and time is:&nbsp;  <font color=&quot;#FF0000&quot;>  <%= new java.util.Date() %> </font></b></td></tr></table></center></div></body></html>
<html> <head> <title>Enter your name</title> </head> <body> <p>&nbsp;</p> <form method=&quot;POST&quot; action=&quot;showname.jsp&quot;> <p><font color=&quot;#800000&quot; size=&quot;5&quot;>Enter your name:</font><input type =&quot;text&quot; name=&quot;username&quot; size=&quot;20&quot;></p> <p><input type=&quot;submit&quot; value=&quot;Submit&quot; name=&quot;B1&quot;></p> </form> </body> </html>
<%@page contentType=&quot;text/html&quot; %>   <!-- http://www.roseindia.net/jsp --> <html> <body> <p><font size=&quot;6&quot;>Welcome :&nbsp; <%=request.getParameter(&quot;username&quot;)%></font></p> </body> </html>
jsp:forward Forwards a request to a web resource.  JSP Syntax <jsp:forward page=&quot;{ relativeURL  | <%=  expression  %>}&quot; />  or   <jsp:forward page=&quot;{ relativeURL  | <%=  expression  %>}&quot; >     <jsp:param name=&quot; parameterName &quot;       value=&quot;{ parameterValue  | <%=  expression  %>}&quot; />  </jsp:forward>  Examples <jsp:forward page=&quot;/servlet/login&quot; />  <jsp:forward page=&quot;/servlet/login&quot;>      <jsp:param name=&quot;username&quot; value=&quot;jsmith&quot; /> </jsp:forward>
jsp:forward The <jsp:forward> element forwards the request object containing the client request information from one JSP page to another resource. The target resource can be an HTML file, another JSP page, or a servlet, as long as it is in the same application context as the forwarding JSP page. The lines in the source JSP page after the <jsp:forward> element are not processed.  You can pass parameter names and values to the target resource by using a <jsp:param> clause. An example of this would be passing the parameter name username (with name=&quot;username&quot;) and the value scott (with value=&quot;scott&quot;) to a servlet as part of the request. If you use <jsp:param>, the target resource should be a dynamic resource that can handle the parameters.  Attributes page=&quot;{ relativeURL  | <%=  expression  %>}&quot;  A String or an expression representing the relative URL of the component to which you are forwarding the request. The component can be another JSP page, a servlet, or any other object that can respond to a request.  The relative URL looks like a path--it cannot contain a protocol name, port number, or domain name. The URL can be absolute or relative to the current JSP page. If it is absolute (beginning with a /), the path is resolved by your web or application server.
jsp:include Includes a static file or the result from another web component.  JSP Syntax <jsp:include page=&quot;{ relativeURL  | <%=  expression  %>}&quot;    flush=&quot;true| false&quot; />  or   <jsp:include page=&quot;{ relativeURL  | <%=  expression  %>}&quot;    flush=&quot;true| false&quot; >      <jsp:param name=&quot; parameterName &quot;       value=&quot;{ parameterValue  | <%=  expression  %>}&quot; /> </jsp:include>
jsp:include The <jsp:include> element allows you to include either a  static  or  dynamic   resource  in a JSP page. The results of including static and dynamic resources are quite different. If the resource is static, its content is included in the calling JSP page. If the resource is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing the remainder of the JSP page.  You cannot always determine from a pathname if a resource is static or dynamic. For example,  http://server:8080/index.html  might map to a servlet through a server alias. The <jsp:include> element handles both types of resources, so it is convenient to use when you don't know whether the resource is static or dynamic.  If the included resource is dynamic, you can use a <jsp:param> clause to pass the name and value of a parameter to the resource. As an example, you could pass the string username and a user's name to a login form that is coded in a JSP page.
jsp:useBean Locates or instantiates a bean with a specific name and scope.  JSP Syntax <jsp:useBean id=&quot; beanInstanceName &quot;    scope=&quot; page |request|session|application&quot;  {      class=&quot; package.class &quot; [ type=&quot; package.class “ ]|      beanName=&quot;{ package.class  | <%=  expression  %>}“         type=&quot; package.class &quot; |       }  { /> | >  other elements  </jsp:useBean> }
jsp:useBean Examples <jsp:useBean id=&quot;cart&quot; scope=&quot;session&quot; class=&quot;session.Carts&quot; /> <jsp:setProperty name=&quot;cart&quot; property=&quot;*&quot; /> <jsp:useBean id=&quot;checking&quot; scope=&quot;session&quot; class=&quot;bank.Checking&quot; >     <jsp:setProperty name=&quot;checking&quot; property=&quot;balance&quot; value=&quot;0.0&quot; /> </jsp:useBean>
jsp:useBean The <jsp:useBean> element locates or instantiates a JavaBeans component. <jsp:useBean> first attempts to locate an instance of the bean. If the bean does not exist, <jsp:useBean> instantiates it from a class or serialized template.  To locate or instantiate the bean, <jsp:useBean> takes the following steps, in this order:  Attempts to locate a bean with the scope and name you specify.  Defines an object reference variable with the name you specify.  If it finds the bean, stores a reference to it in the variable. If you specified type, gives the bean that type.  If it does not find the bean, instantiates it from the class you specify, storing a reference to it in the new variable.  If <jsp:useBean> has  instantiated  (rather than located) the bean, and if it has body tags or elements (between <jsp:useBean> and </jsp:useBean>), executes the body tags.
jsp:useBean The body of a <jsp:useBean> element often contains a <jsp:setProperty> element that sets property values in the bean. As described in  Step 5 , the body tags are only processed if <jsp:useBean> instantiates the bean. If the bean already exists and <jsp:useBean> locates it, the body tags have no effect.  id=&quot; beanInstanceName &quot;  A variable that identifies the bean in the scope you specify. You can use the variable name in expressions or scriptlets in the JSP page.  The name is case sensitive and must conform to the naming conventions of the scripting language used in the JSP page. If you use the Java programming language, the conventions in the  Java Language Specification . If the bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used in the original <jsp:useBean> element.
jsp:useBean scope=&quot; page |request|session|application&quot;  The scope in which the bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below:  page   You can use the bean within the JSP page with the <jsp:useBean> element or any of the page's static include files, until the page sends a response back to the client or forwards a request to another resource.  request   You can use the bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another resource. You can use the request object to access the bean, for example, request.getAttribute( beanInstanceName ).  session   You can use the bean from any JSP page in the same session as the JSP page that created the bean. The bean exists across the entire session, and any page that participates in the session can use it. The page in which you create the bean must have a page directive with session=&quot;true&quot;.  application   You can use the bean from any JSP page in the same application as the JSP page that created the bean. The bean exists across an entire JSP application, and any page in the application can use the bean.
jsp:useBean class=&quot; package.class &quot;  Instantiates a bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor. The package and class name are case sensitive.  type=&quot; package.class &quot;  If the bean already exists in the scope, gives the bean a data type other than the class from which it was instantiated. The value of type must be a superclass of class or an interface implemented by class.  If you use type without class or beanName, no bean is instantiated. The package and class name are case sensitive.
jsp:useBean class=&quot; package.class &quot; type=&quot; package.class &quot;  Instantiates a bean from the class named in class and assigns the bean the data type you specify in type. The value of type can be the same as class, a superclass of class, or an interface implemented by class.  The class you specify in class must not be abstract and must have a public, no-argument constructor. The package and class names you use with both class and type are case sensitive.
jsp:setProperty Sets a property value or values in a bean.  JSP Syntax <jsp:setProperty name=&quot; beanInstanceName &quot;  {    property=&quot;*&quot; |    property=&quot; propertyName &quot; [ param=&quot; parameterName &quot; ] |    property=&quot; propertyName &quot; value=&quot;{ stringLiteral | <%=  expression  %>}&quot; } />  Examples <jsp:setProperty name=&quot;mybean&quot; property=&quot;*&quot; /> <jsp:setProperty name=&quot;mybean&quot; property=&quot;username&quot; /> <jsp:setProperty name=&quot;mybean&quot; property=&quot;username&quot; value=&quot;Steve&quot; />
jsp:setProperty Description The < jsp:setProperty > element sets the value of one or more properties in a bean, using the bean's setter methods. You must declare the bean with  < jsp:useBean >   before  you set a property value with <jsp:setProperty>. Because < jsp:useBean > and <jsp:setProperty> work together, the bean instance names they use must match (that is, the value of name in < jsp:setProperty > and the value of id in <jsp:useBean> must be the same).  You can use < jsp:setProperty > to set property values in several ways:  By passing all of the values the user enters (stored as parameters in the request object) to matching properties in the bean  By passing a specific value the user enters to a specific property in the bean  By setting a bean property to a value you specify as either a String or an expression that is evaluated at runtime  Each method of setting property values has its own syntax, as described in the next section.
jsp:setProperty Attributes and Usage name=&quot; beanInstanceName &quot;  The name of an instance of a bean that has already been created or located with a <jsp:useBean> element. The value of name must match the value of id in <jsp:useBean>. The <jsp:useBean> element must appear before <jsp:setProperty> in the JSP page.  property=&quot;*&quot;  Stores all of the values of request parameters in bean properties. The names of the bean properties must match the names of the request parameters. A bean property is usually defined by a variable declaration with matching getter and setter methods
jsp:setProperty property=&quot; propertyName &quot; [ param=&quot; parameterName &quot; ]  Sets one bean property to the value of one request parameter. In the syntax, property specifies the name of the bean property and param specifies the name of the request parameter by which data is being sent from the client to the server.  If the bean property and the request parameter have different names, you must specify both property and param. If they have the same name, you can specify property and omit param.  If a parameter has an empty or null value, the corresponding bean property is not set.  property=&quot; propertyName &quot; value=&quot;{ string  | <%=  expression  %>}&quot;  Sets one bean property to a specific value. The value can be a String or an expression that is evaluated at runtime. If the value is a String, it is converted to the bean property's data type according to the conversion rules shown above in  TABLE 1 . If it is an expression, its value must have a data type that matches the the data type of the value of the expression must match the data type of the bean property.
jsp:getProperty Inserts the value of a bean property into the result.  JSP Syntax < jsp:getProperty  name=&quot; beanInstanceName &quot; property=&quot; propertyName &quot; />  XML Syntax < jsp:getProperty  name=&quot; beanInstanceName &quot; property=&quot; propertyName &quot; />  Examples <jsp:useBean id=&quot;calendar&quot; scope=&quot;page&quot; class=&quot;employee.Calendar&quot; /> <h2> Calendar of  <jsp:getProperty name=&quot;calendar&quot; property=&quot;username&quot; /> </h2>
jsp:getProperty The < jsp:getProperty > element gets a bean property value using the property's getter methods and inserts the value into the response. You must create or locate a bean with  < jsp:useBean >   before  you use <jsp:getProperty>.
jsp:useBean Example < html >< body > < form  method=‘post’ action=‘usebeanexample.jsp’> Name:< input  type=‘text’ name=‘name’/><br> Branch:< input  type=‘text’ name=‘address’/><br> RollNo:< input  type=‘text’ name=‘rollNo’/><br> Date of Birth:< input  type=‘text’ name=‘dob’/><br> < input  type=‘submit’/><input type=‘reset’/> </ form > </ body ></ html >
jsp:useBean Example public   class  Student{ String name,address,rollNo,dob; public  Student(){} String getName(){  return  name;} String setName(String name){this.name=name;} String geAddress(){  return  address;} String setAddress(String address){this.address=address;} String getRollNo(){  return  rollNo;} String setRollNo(String rollNo){this.rollNo=rollNo;} String getDOB(){  return  dob;} String setDOB(String dob){this.dob=dob;} }
jsp:usebean Example Usebeanexample.jsp <%@page  language=‘java’ %> < jsp:useBean  id=‘stuobj’ class=“Student” scope=‘request’> < jsp:setProperty  name=‘stuobj’ property=‘name’/> < jsp:setProperty  name=‘stuobj’ property=‘address’/> < jsp:setProperty  name=‘stuobj’ property=‘rollNo’ param=‘rollNo’/> < jsp:setProperty  name=‘stuobj’ property=‘DOB’ param=‘dob’/> </jsp:useBean> <% out.print(“student name is”+stuobj.getName());  %>
JSP Implicit Objects Object Name Type request HttpServletRequest response HttpServletResponse application ServletContext Session HttpSession page Object config ServletConfig pageContext PageContext Out JspWriter Exception Throwable
JSP session object

More Related Content

PPTX
PPS
Jsp chapter 1
PPTX
JSP Directives
PPTX
Jsp presentation
PPTX
Intro to React
PDF
React JS - Introduction
PPTX
React workshop presentation
PPTX
React-JS.pptx
Jsp chapter 1
JSP Directives
Jsp presentation
Intro to React
React JS - Introduction
React workshop presentation
React-JS.pptx

What's hot (20)

PPT
PHP - Introduction to PHP AJAX
PDF
Basics of React Hooks.pptx.pdf
PPSX
Java annotations
PPTX
Sharing Data Between Angular Components
PPTX
Ajax ppt - 32 slides
PPTX
ReactJS presentation.pptx
PPTX
PDF
Workshop 21: React Router
PPTX
Java Strings
PPTX
Presentation on "An Introduction to ReactJS"
PPT
Jsp(java server pages)
PDF
Important React Hooks
PPT
Asynchronous JavaScript & XML (AJAX)
PPTX
reactJS
PPTX
React js programming concept
PDF
JavaScript - Chapter 7 - Advanced Functions
PPTX
Servlets
PPTX
Ajax
PPTX
servlet in java
PHP - Introduction to PHP AJAX
Basics of React Hooks.pptx.pdf
Java annotations
Sharing Data Between Angular Components
Ajax ppt - 32 slides
ReactJS presentation.pptx
Workshop 21: React Router
Java Strings
Presentation on "An Introduction to ReactJS"
Jsp(java server pages)
Important React Hooks
Asynchronous JavaScript & XML (AJAX)
reactJS
React js programming concept
JavaScript - Chapter 7 - Advanced Functions
Servlets
Ajax
servlet in java
Ad

Similar to JSP (20)

PPT
PPT
29 Jsp
PPTX
JSP.pptx
PPT
JSP diana y yo
PDF
PPTX
Java Server Pages
PDF
Java Web Programming [4/9] : JSP Basic
PPT
Jsp sasidhar
PPTX
Introduction - Java Server Programming (JSP)
PPTX
JSP- JAVA SERVER PAGES
PPTX
JSP AND XML USING JAVA WITH GET AND POST METHODS
PPTX
WT Unit-Vuufvmjn dissimilating Dunkirk k
PPT
Java Server Pages
PPT
Java serverpages
PPTX
C:\fakepath\jsp01
PPTX
Web programming-Introduction to JSP.pptx
PPT
Jsp ppt
PPTX
Learning jsp
PDF
JSP Components and Directives.pdf
29 Jsp
JSP.pptx
JSP diana y yo
Java Server Pages
Java Web Programming [4/9] : JSP Basic
Jsp sasidhar
Introduction - Java Server Programming (JSP)
JSP- JAVA SERVER PAGES
JSP AND XML USING JAVA WITH GET AND POST METHODS
WT Unit-Vuufvmjn dissimilating Dunkirk k
Java Server Pages
Java serverpages
C:\fakepath\jsp01
Web programming-Introduction to JSP.pptx
Jsp ppt
Learning jsp
JSP Components and Directives.pdf
Ad

More from vikram singh (20)

PPTX
PPT
Enterprise java beans(ejb) Update 2
PDF
Web tech importants
PPT
Enterprise Java Beans( E)
PPT
Enterprise java beans(ejb) update 2
PPT
Enterprise java beans(ejb)
DOC
2 4 Tree
DOC
23 Tree Best Part
DOC
JSP Scope variable And Data Sharing
PPT
Bean Intro
PPT
PPT
Sax Dom Tutorial
PPT
PPT
PPT
Xml Schema
PPT
Request dispatching in servlet
PPT
Servlet Part 2
DOC
Tutorial Solution
DOC
Java Script Language Tutorial
PPT
Web Tech Java Servlet Update1
Enterprise java beans(ejb) Update 2
Web tech importants
Enterprise Java Beans( E)
Enterprise java beans(ejb) update 2
Enterprise java beans(ejb)
2 4 Tree
23 Tree Best Part
JSP Scope variable And Data Sharing
Bean Intro
Sax Dom Tutorial
Xml Schema
Request dispatching in servlet
Servlet Part 2
Tutorial Solution
Java Script Language Tutorial
Web Tech Java Servlet Update1

Recently uploaded (20)

PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Empathic Computing: Creating Shared Understanding
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Modernizing your data center with Dell and AMD
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Unlocking AI with Model Context Protocol (MCP)
Machine learning based COVID-19 study performance prediction
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Empathic Computing: Creating Shared Understanding
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
NewMind AI Monthly Chronicles - July 2025
Encapsulation_ Review paper, used for researhc scholars
Modernizing your data center with Dell and AMD
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Advanced methodologies resolving dimensionality complications for autism neur...
Understanding_Digital_Forensics_Presentation.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Approach and Philosophy of On baking technology
Dropbox Q2 2025 Financial Results & Investor Presentation
The Rise and Fall of 3GPP – Time for a Sabbatical?
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

JSP

  • 1. Java Server Pages Java server pages is a technology for developing portable java web applications that runs on a java web server. Main motivation behind developing JSP was to develop a technology so that a non-java programmer or a person with little knowledge of java could write web applications for java plaform. Initially JSP was developed to replace servlet but now common practice is to use servlet and jsp together using MVC(model-view-controller) pattern. JSP allows developer to write html (static content),jsp action tags and java (dynamic content) code in the same page. JSPs are compiled into java servlets by a jsp compiler, thus internally jsp page is converted into servlet, it is must to understand java servlet technology throughly for becoming a good jsp programmer.
  • 2. Java Server Pages JSP enables you to separate the dynamic content of a web page from its presentation. It caters to different types of developes. Web designers, who are responsible for the graphical design of the page Java developers, who write the code to generate dynamic content.
  • 3. JSP Life Cycle JSP life cycle includes following steps/phases: JSP page translation – generate servlet source code The translation occurs only when jsp page has to serve its first request. Translation does not have to happen again unless the page is updated. JSP page compilation – compile generated code into byte code Load class Create instance Call the jspInit method Call the _jspService method - for each request Call the jspDestroy method
  • 4. Deploying JSP User don’t need to register jsp pages in deployment descriptor file web.xml. Just place them in the accessible area of a web application directory structure and user can access them. How ever you can register a jsp page same way as a servlet. You even use the <servlet> element with one vital difference – where the <servlet-class> would apper,you substitute <jsp-file> instead. <servlet> <servlet-name>JspName1<servlet-name> <jsp-file>/instanceCheck.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>JspName1</servlet-name> <url-pattern>/jspName2</url-pattern> </servlet-mapping>
  • 5. Deploying JSP Now you can access jsp page in following two ways http://localhost:8080/myapp/instanceCheck.jsp OR http://localhost:8080/myapp/jspName2 if you want to supress direct access to jsp , locate jsp page under WEB-INF directory.
  • 6.  
  • 7. JSP API Translated JSP Servlet implements javax.serlvet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage. The javax.servlet.jsp.JspPage interface contains two methods: 1. public void jspInit() - This method is invoked when the JSP is initialized and the page authors are free to provide initialization of the JSP by implementing this method in their JSPs. 2. public void jspDestroy() - This method is invoked when the JSP is about to be destroyed by the container. Similar to above, page authors can provide their own implementation. The javax.servlet.jsp.HttpJspPage interface contains one method: public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException This method generated by the JSP container is invoked, every time a request comes to the JSP. The request is processed and the JSP generates appropriate response. This response is taken by the container and passed back to the client.
  • 8. Java Server Pages JSP Elements Directives Scripting Elements JSP Actions Templates
  • 9. JSP Scripting Elements There are four types of scripting elements defined Declaration Expression Scriptlets Comments
  • 10. Declaration Declares a variable or method valid in the scripting language used in the JSP page. JSP Syntax <%! declaration; [ declaration; ]+ ... %> XML Syntax <jsp:declaration>      code fragment [ declaration; ]+ ... </jsp:declaration> Examples <%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>
  • 11. Declaration A declaration declares one or more variables or methods that you can use in Java code later in the JSP page. You must declare the variable or method before you use it in the JSP page. You can declare any number of variables or methods within one declaration element, as long as you end each declaration with a semicolon. The declaration must be valid in the Java programming language. You can use declaration to write anything that would be placed in the generated servlet outside of the _jspService method. You can place in your declaration any code that can appear in a servlet soure file; instance methods, static methods, inner classes . You can also use declarations to override some methods that appear further up in the jsp servlet hierarchy – namely jspInit and jspDestroy.
  • 12. Expression Contains an expression valid in the scripting language used in the JSP page. JSP Syntax <%= expression %> XML Syntax <jsp:expression>     expression </jsp:expression> Description An expression element contains a scripting language expression that is evaluated, converted to a String, and inserted into the response where the expression appears in the JSP page. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP page. Example Welcome, <%=userName%> Output: Welcome, James
  • 13. Expression <%= new java.util.Date()%> When this is generated into servlet code, the resulting java stmt will probably look like this: out.print(new java.util.Date()); Out is an instance of javax.servlet.http.jsp.JspWriter and it is associated with the response for the generated servlet. Cotents of your jsp expression are used directly as the parameter to the print() method.so it must not end with semicolon.
  • 14. Script lets Contains a code fragment valid in the page scripting language. Scriptlets allows you to include a series of java statements inside the _jspService method that are executed on every request to the page.these java stmts are incorporated into _jspService method as it is.so you must terminate them with semicolon. JSP Syntax <% code fragment %> OR <jsp:scriptlet>     code fragment </jsp:scriptlet>
  • 15. Scriptlets Examples <%  String name = null;     if (request.getParameter(&quot;name&quot;) == null) { %> <%@ include file=&quot;error.html&quot; %> <%   } else {     userObject.setName(request.getParameter(&quot;name&quot;));     } %>
  • 16. Comments To denote any lines you want to be completely ignored by the JSP translation process. Example <%-- Author: James Gosling --%>
  • 17. JSP Directives Directives are instructions to jsp compiler. Those intructions tell the compiler that some action needs to be taken. General syntax for directives is: <%@ Directive-name attribute-value pairs %> There are three main directives defined in jsp Page Include Taglib
  • 18. Page Directive Page Directive- Defines attributes that apply to an entire JSP page. JSP Syntax <%@ page  language=&quot; java &quot; import=&quot;{ package.class | package.* }, ...&quot;   ,   session=&quot; true |false&quot;  %> OR <jsp:directive.page pageDirectiveAttrList /> where pageDirectiveAttrList is the same as the list in the JSP syntax. XML Syntax <jsp:directive.page pageDirectiveAttrList /> where pageDirectiveAttrList is the same as the list in the JSP syntax. Examples <%@ page import=&quot;java.util.*, java.lang.*&quot; %> <%@ page buffer=&quot;5kb&quot; autoFlush=&quot;false&quot; %> <jsp:directive.page errorPage=&quot;error.jsp&quot; />
  • 19. Page Directive Description The page directive applies to an entire JSP page and any of its static include files , which together are called a translation unit . A static include file is a file whose content becomes part of the calling JSP page. The page directive does not apply to any dynamic resources; see < jsp:include > for more information. You can use the page directive more than once in a translation unit, but you can only use each attribute, except import, once. Because the import attribute is similar to the import statement in the Java programming language, you can use a page directive with import more than once in a JSP page or translation unit. No matter where you position the page directive in a JSP page or included files, it applies to the entire translation unit. However, it is often good programming style to place it at the top of the JSP page.
  • 20. Page Directive Attributes language=&quot; java &quot; The scripting language used in scriptlets, declarations, and expressions in the JSP page and any included files. In v2.0, the only allowed value is java. extends=&quot; package.class &quot; The fully qualified name of the superclass of the Java class this JSP page will be compiled to. Use this attribute cautiously, as it can limit the JSP container's ability to provide a specialized superclass that improves the quality of the compiled class.
  • 21. Page Directive import=&quot;{ package.class | package.* }, ...&quot; A comma-separated list of Java packages that the JSP page should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP page. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP page. The following packages are implicitly imported, so you don't need to specify them with the import attribute: java.lang.* javax.servlet.* javax.servlet.jsp.* javax.servlet.http.* You must place the import attribute before the element that calls the imported class.
  • 22. Page Directive isThreadSafe=&quot; true |false&quot; Whether thread safety is implemented in the JSP page. The default value is true, which means that the JSP container can send multiple, concurrent client requests to the JSP page. You must write code in the JSP page to synchronize the multiple client threads. If you use false, the JSP container sends client requests one at a time to the JSP page. info=&quot; text &quot; A text string that is incorporated verbatim into the compiled JSP page. You can later retrieve the string with the Servlet.getServletInfo() method. errorPage=&quot; relativeURL &quot; A pathname to a JSP page that this JSP page sends exceptions to. If the pathname begins with a /, the path is relative to the JSP application's document root directory and is resolved by the web server. If not, the pathname is relative to the current JSP page.
  • 23. Page Directive isErrorPage=&quot;true| false &quot; Whether the JSP page displays an error page. If set to true, you can use the exception object in the JSP page. If set to false (the default value), you cannot use the exception object in the JSP page. contentType=&quot; mimeType [; charset= characterSet ]&quot; |     &quot; text/html;charset=ISO-8859-1 &quot; The MIME type and character encoding the JSP page uses for the response. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1. pageEncoding=&quot; characterSet | ISO-8859-1 &quot; The character encoding the JSP page uses for the response. The default character set is ISO-8859-1.
  • 24. Include Directive Includes a static file in a JSP page, parsing the file's JSP elements. JSP Syntax <%@ include file=&quot; relativeURL &quot; %> OR <jsp:directive.include file=&quot; relativeURL &quot; /> XML Syntax <jsp:directive.include file=&quot; relativeURL &quot; /> Examples include.jsp: <html> <head> <title>An Include Test</title> </head> <body bgcolor=&quot;white&quot;> <font color=&quot;blue&quot;> The current date and time are <%@ include file=&quot;date.jsp&quot; %> </font> </body> </html>
  • 25. Include Directive date.jsp <%@ page import=&quot;java.util.*&quot; %> <%= (new java.util.Date() ).toLocaleString() %> Displays in the page: The current date and time are Aug 30, 1999 2:38:40 Description An include directive inserts a file of text or code in a JSP page at translation time, when the JSP page is compiled. When you use the include directive, the include process is static . A static include means that the text of the included file is added to the JSP page. The included file can be a JSP page, HTML file, XML document, or text file. If the included file is a JSP page, its JSP elements are translated and included (along with any other text) in the JSP page. Once the included file is translated and included, the translation process resumes with the next line of the including JSP page.
  • 26. Include Directive Attributes file=&quot; relativeURL &quot; The pathname to the included file, which is always a relative URL. A relative URL is just the path segment of an URL, without a protocol, port, or domain name, like this: &quot;error.jsp&quot; &quot;/templates/onlinestore.html&quot; &quot;/beans/calendar.jsp&quot; If the relative URL starts with /, the path is relative to the JSP application's context, which is a javax.servlet.ServletContext object that is in turn stored in the application object. If the relative URL starts with a directory or file name, the path is relative to the JSP page.
  • 27. taglib directive Defines a tag library and prefix for the custom tags used in the JSP page. JSP Syntax <%@ taglib {uri=&quot; URI &quot; | tagdir=&quot;/WEB-INF/tags[/ subdir ]+&quot;} prefix=&quot; tagPrefix &quot; %> Examples <%@ taglib uri=&quot;http://www.jspcentral.com/tags&quot; prefix=&quot;public&quot; %> <public:loop>    ... </public:loop> Description The taglib directive declares that the JSP page uses custom tags, names the tag library that defines them, and specifies their tag prefix. You must use a taglib directive before you use the custom tag in a JSP page. You can use more than one taglib directive in a JSP page, but the prefix defined in each must be unique.
  • 28. taglib Directive Attributes uri =&quot; URI &quot;- The Uniform Resource Identifier (URI) that uniquely locates the TLD that describes the set of custom tags associated with the named tag prefix. Prefix =‘tagprefix’ The prefix that precedes the custom tag name, for example, public in <public:loop>. Empty prefixes are illegal. If you are developing or using custom tags, you cannot use the tag prefixes jsp, jspx, java, javax, servlet, sun, and sunw, as they are reserved by Sun Microsystems.
  • 29. JSP ACTIONS Servlet container provides many built in functionality to ease the development of the applications Programmers can use these functions in JSP applications. The JSP Actions tags enables the programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page. Here is the list of JSP Actions: jsp:include  The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page.   jsp:param   The jsp:param action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block.  jsp:forward   The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page.   
  • 30. JSP ACTIONS jsp:getProperty  The jsp:getPropertyB is used to get specified property from the JavaBean object.    jsp:setProperty   The jsp:setProperty tag is used to set a property in the JavaBean object.    jsp:useBean   The jsp:useBean   tag is used to instantiate an object of Java Bean or it can re-use existing java bean object.
  • 31. Simple JSP Example <%@page contentType=&quot;text/html&quot; import=&quot;java.util.*&quot; %> <html> <body> <p>&nbsp;</p><div align=&quot;center&quot;><center> <table border=&quot;0&quot; cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; width=&quot;460&quot; bgcolor=&quot;#EEFFCA&quot;> <tr> <td width=&quot;100%&quot;><font size=&quot;6&quot; color =&quot;#008000&quot;>&nbsp;Date Example</font></td> </tr> <tr><td width=&quot;100%&quot;><b>&nbsp;Current Date and time is:&nbsp; <font color=&quot;#FF0000&quot;> <%= new java.util.Date() %> </font></b></td></tr></table></center></div></body></html>
  • 32. <html> <head> <title>Enter your name</title> </head> <body> <p>&nbsp;</p> <form method=&quot;POST&quot; action=&quot;showname.jsp&quot;> <p><font color=&quot;#800000&quot; size=&quot;5&quot;>Enter your name:</font><input type =&quot;text&quot; name=&quot;username&quot; size=&quot;20&quot;></p> <p><input type=&quot;submit&quot; value=&quot;Submit&quot; name=&quot;B1&quot;></p> </form> </body> </html>
  • 33. <%@page contentType=&quot;text/html&quot; %> <!-- http://www.roseindia.net/jsp --> <html> <body> <p><font size=&quot;6&quot;>Welcome :&nbsp; <%=request.getParameter(&quot;username&quot;)%></font></p> </body> </html>
  • 34. jsp:forward Forwards a request to a web resource. JSP Syntax <jsp:forward page=&quot;{ relativeURL | <%= expression %>}&quot; /> or <jsp:forward page=&quot;{ relativeURL | <%= expression %>}&quot; >     <jsp:param name=&quot; parameterName &quot;       value=&quot;{ parameterValue | <%= expression %>}&quot; /> </jsp:forward> Examples <jsp:forward page=&quot;/servlet/login&quot; /> <jsp:forward page=&quot;/servlet/login&quot;>      <jsp:param name=&quot;username&quot; value=&quot;jsmith&quot; /> </jsp:forward>
  • 35. jsp:forward The <jsp:forward> element forwards the request object containing the client request information from one JSP page to another resource. The target resource can be an HTML file, another JSP page, or a servlet, as long as it is in the same application context as the forwarding JSP page. The lines in the source JSP page after the <jsp:forward> element are not processed. You can pass parameter names and values to the target resource by using a <jsp:param> clause. An example of this would be passing the parameter name username (with name=&quot;username&quot;) and the value scott (with value=&quot;scott&quot;) to a servlet as part of the request. If you use <jsp:param>, the target resource should be a dynamic resource that can handle the parameters. Attributes page=&quot;{ relativeURL | <%= expression %>}&quot; A String or an expression representing the relative URL of the component to which you are forwarding the request. The component can be another JSP page, a servlet, or any other object that can respond to a request. The relative URL looks like a path--it cannot contain a protocol name, port number, or domain name. The URL can be absolute or relative to the current JSP page. If it is absolute (beginning with a /), the path is resolved by your web or application server.
  • 36. jsp:include Includes a static file or the result from another web component. JSP Syntax <jsp:include page=&quot;{ relativeURL | <%= expression %>}&quot;    flush=&quot;true| false&quot; /> or <jsp:include page=&quot;{ relativeURL | <%= expression %>}&quot;    flush=&quot;true| false&quot; >      <jsp:param name=&quot; parameterName &quot;       value=&quot;{ parameterValue | <%= expression %>}&quot; /> </jsp:include>
  • 37. jsp:include The <jsp:include> element allows you to include either a static or dynamic resource in a JSP page. The results of including static and dynamic resources are quite different. If the resource is static, its content is included in the calling JSP page. If the resource is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing the remainder of the JSP page. You cannot always determine from a pathname if a resource is static or dynamic. For example, http://server:8080/index.html might map to a servlet through a server alias. The <jsp:include> element handles both types of resources, so it is convenient to use when you don't know whether the resource is static or dynamic. If the included resource is dynamic, you can use a <jsp:param> clause to pass the name and value of a parameter to the resource. As an example, you could pass the string username and a user's name to a login form that is coded in a JSP page.
  • 38. jsp:useBean Locates or instantiates a bean with a specific name and scope. JSP Syntax <jsp:useBean id=&quot; beanInstanceName &quot;    scope=&quot; page |request|session|application&quot; {     class=&quot; package.class &quot; [ type=&quot; package.class “ ]|     beanName=&quot;{ package.class | <%= expression %>}“        type=&quot; package.class &quot; |     } { /> | > other elements </jsp:useBean> }
  • 39. jsp:useBean Examples <jsp:useBean id=&quot;cart&quot; scope=&quot;session&quot; class=&quot;session.Carts&quot; /> <jsp:setProperty name=&quot;cart&quot; property=&quot;*&quot; /> <jsp:useBean id=&quot;checking&quot; scope=&quot;session&quot; class=&quot;bank.Checking&quot; >     <jsp:setProperty name=&quot;checking&quot; property=&quot;balance&quot; value=&quot;0.0&quot; /> </jsp:useBean>
  • 40. jsp:useBean The <jsp:useBean> element locates or instantiates a JavaBeans component. <jsp:useBean> first attempts to locate an instance of the bean. If the bean does not exist, <jsp:useBean> instantiates it from a class or serialized template. To locate or instantiate the bean, <jsp:useBean> takes the following steps, in this order: Attempts to locate a bean with the scope and name you specify. Defines an object reference variable with the name you specify. If it finds the bean, stores a reference to it in the variable. If you specified type, gives the bean that type. If it does not find the bean, instantiates it from the class you specify, storing a reference to it in the new variable. If <jsp:useBean> has instantiated (rather than located) the bean, and if it has body tags or elements (between <jsp:useBean> and </jsp:useBean>), executes the body tags.
  • 41. jsp:useBean The body of a <jsp:useBean> element often contains a <jsp:setProperty> element that sets property values in the bean. As described in Step 5 , the body tags are only processed if <jsp:useBean> instantiates the bean. If the bean already exists and <jsp:useBean> locates it, the body tags have no effect. id=&quot; beanInstanceName &quot; A variable that identifies the bean in the scope you specify. You can use the variable name in expressions or scriptlets in the JSP page. The name is case sensitive and must conform to the naming conventions of the scripting language used in the JSP page. If you use the Java programming language, the conventions in the Java Language Specification . If the bean has already been created by another <jsp:useBean> element, the value of id must match the value of id used in the original <jsp:useBean> element.
  • 42. jsp:useBean scope=&quot; page |request|session|application&quot; The scope in which the bean exists and the variable named in id is available. The default value is page. The meanings of the different scopes are shown below: page   You can use the bean within the JSP page with the <jsp:useBean> element or any of the page's static include files, until the page sends a response back to the client or forwards a request to another resource. request   You can use the bean from any JSP page processing the same request, until a JSP page sends a response to the client or forwards the request to another resource. You can use the request object to access the bean, for example, request.getAttribute( beanInstanceName ). session   You can use the bean from any JSP page in the same session as the JSP page that created the bean. The bean exists across the entire session, and any page that participates in the session can use it. The page in which you create the bean must have a page directive with session=&quot;true&quot;. application   You can use the bean from any JSP page in the same application as the JSP page that created the bean. The bean exists across an entire JSP application, and any page in the application can use the bean.
  • 43. jsp:useBean class=&quot; package.class &quot; Instantiates a bean from a class, using the new keyword and the class constructor. The class must not be abstract and must have a public, no-argument constructor. The package and class name are case sensitive. type=&quot; package.class &quot; If the bean already exists in the scope, gives the bean a data type other than the class from which it was instantiated. The value of type must be a superclass of class or an interface implemented by class. If you use type without class or beanName, no bean is instantiated. The package and class name are case sensitive.
  • 44. jsp:useBean class=&quot; package.class &quot; type=&quot; package.class &quot; Instantiates a bean from the class named in class and assigns the bean the data type you specify in type. The value of type can be the same as class, a superclass of class, or an interface implemented by class. The class you specify in class must not be abstract and must have a public, no-argument constructor. The package and class names you use with both class and type are case sensitive.
  • 45. jsp:setProperty Sets a property value or values in a bean. JSP Syntax <jsp:setProperty name=&quot; beanInstanceName &quot; {    property=&quot;*&quot; |    property=&quot; propertyName &quot; [ param=&quot; parameterName &quot; ] |    property=&quot; propertyName &quot; value=&quot;{ stringLiteral | <%= expression %>}&quot; } /> Examples <jsp:setProperty name=&quot;mybean&quot; property=&quot;*&quot; /> <jsp:setProperty name=&quot;mybean&quot; property=&quot;username&quot; /> <jsp:setProperty name=&quot;mybean&quot; property=&quot;username&quot; value=&quot;Steve&quot; />
  • 46. jsp:setProperty Description The < jsp:setProperty > element sets the value of one or more properties in a bean, using the bean's setter methods. You must declare the bean with < jsp:useBean > before you set a property value with <jsp:setProperty>. Because < jsp:useBean > and <jsp:setProperty> work together, the bean instance names they use must match (that is, the value of name in < jsp:setProperty > and the value of id in <jsp:useBean> must be the same). You can use < jsp:setProperty > to set property values in several ways: By passing all of the values the user enters (stored as parameters in the request object) to matching properties in the bean By passing a specific value the user enters to a specific property in the bean By setting a bean property to a value you specify as either a String or an expression that is evaluated at runtime Each method of setting property values has its own syntax, as described in the next section.
  • 47. jsp:setProperty Attributes and Usage name=&quot; beanInstanceName &quot; The name of an instance of a bean that has already been created or located with a <jsp:useBean> element. The value of name must match the value of id in <jsp:useBean>. The <jsp:useBean> element must appear before <jsp:setProperty> in the JSP page. property=&quot;*&quot; Stores all of the values of request parameters in bean properties. The names of the bean properties must match the names of the request parameters. A bean property is usually defined by a variable declaration with matching getter and setter methods
  • 48. jsp:setProperty property=&quot; propertyName &quot; [ param=&quot; parameterName &quot; ] Sets one bean property to the value of one request parameter. In the syntax, property specifies the name of the bean property and param specifies the name of the request parameter by which data is being sent from the client to the server. If the bean property and the request parameter have different names, you must specify both property and param. If they have the same name, you can specify property and omit param. If a parameter has an empty or null value, the corresponding bean property is not set. property=&quot; propertyName &quot; value=&quot;{ string | <%= expression %>}&quot; Sets one bean property to a specific value. The value can be a String or an expression that is evaluated at runtime. If the value is a String, it is converted to the bean property's data type according to the conversion rules shown above in TABLE 1 . If it is an expression, its value must have a data type that matches the the data type of the value of the expression must match the data type of the bean property.
  • 49. jsp:getProperty Inserts the value of a bean property into the result. JSP Syntax < jsp:getProperty name=&quot; beanInstanceName &quot; property=&quot; propertyName &quot; /> XML Syntax < jsp:getProperty name=&quot; beanInstanceName &quot; property=&quot; propertyName &quot; /> Examples <jsp:useBean id=&quot;calendar&quot; scope=&quot;page&quot; class=&quot;employee.Calendar&quot; /> <h2> Calendar of <jsp:getProperty name=&quot;calendar&quot; property=&quot;username&quot; /> </h2>
  • 50. jsp:getProperty The < jsp:getProperty > element gets a bean property value using the property's getter methods and inserts the value into the response. You must create or locate a bean with < jsp:useBean > before you use <jsp:getProperty>.
  • 51. jsp:useBean Example < html >< body > < form method=‘post’ action=‘usebeanexample.jsp’> Name:< input type=‘text’ name=‘name’/><br> Branch:< input type=‘text’ name=‘address’/><br> RollNo:< input type=‘text’ name=‘rollNo’/><br> Date of Birth:< input type=‘text’ name=‘dob’/><br> < input type=‘submit’/><input type=‘reset’/> </ form > </ body ></ html >
  • 52. jsp:useBean Example public class Student{ String name,address,rollNo,dob; public Student(){} String getName(){ return name;} String setName(String name){this.name=name;} String geAddress(){ return address;} String setAddress(String address){this.address=address;} String getRollNo(){ return rollNo;} String setRollNo(String rollNo){this.rollNo=rollNo;} String getDOB(){ return dob;} String setDOB(String dob){this.dob=dob;} }
  • 53. jsp:usebean Example Usebeanexample.jsp <%@page language=‘java’ %> < jsp:useBean id=‘stuobj’ class=“Student” scope=‘request’> < jsp:setProperty name=‘stuobj’ property=‘name’/> < jsp:setProperty name=‘stuobj’ property=‘address’/> < jsp:setProperty name=‘stuobj’ property=‘rollNo’ param=‘rollNo’/> < jsp:setProperty name=‘stuobj’ property=‘DOB’ param=‘dob’/> </jsp:useBean> <% out.print(“student name is”+stuobj.getName()); %>
  • 54. JSP Implicit Objects Object Name Type request HttpServletRequest response HttpServletResponse application ServletContext Session HttpSession page Object config ServletConfig pageContext PageContext Out JspWriter Exception Throwable