JSP Standard ActionsAgenda:
Introduction :case 1 : problempublic class JspDemoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uname=request.getParameter("userName"); request.setAttribute("UserName", uname); RequestDispatcher rd=request.getRequestDispatcher("view.jsp"); rd.forward(request, response); } }view.jsp Welcome to : <%= (String)request.getAttribute("UserName") %> OR case 2 :public class JspDemoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uname=request.getParameter("userName"); foo.Person p=new foo.Person(); p.setName(uname); request.setAttribute("person",p); RequestDispatcher rd=request.getRequestDispatcher("view1.jsp"); rd.forward(request, response); } }view1.jsp Welcome to : <%@page import="foo.Person"%> Welcome to : <% Person p=(Person)request.getAttribute("person"); out.println(p.getName()); %>Person.java package foo; public class Person { String name; public void setName(String name) { this.name=name; } public String getName() { return name; } } Solution : view1.jsp <jsp:useBean id="person" class="foo.Person" scope="request" /> Welcome to : <jsp:getProperty property="name" name="person" /> Problem : demo.jsp <%! public int squareIt(int n){ return n*n; } %> <h1>The square of 4 is : <%= squareIt(4) %></h1> <h1>The square of 2 is : <%= squareIt(2) %></h1>This approach has several serious dis-advantages :
package foo; public class Calculator { public int squareIt(){ return n*n; } }view.jsp <jsp:useBean id="calc" class="foo.Calculator" scope="session" /> The square of 4 is : <%= calc.squareIt(4) %>This approach has several advantages :
Note : It is never recommended to write scriptlets, expressions, declarations and business logic with in the Jsp. java bean : java bean is a simple java class To use useBean inside jsp the bean class has to follow the following rules
Jsp Standard Actions :<jsp:useBean> :We can use this tag to make bean functionality available to the Jsp, There are 2 forms of <jsp:useBean>without body : <jsp:useBean id="c" class="CustomerBean" /> with body : <jsp:useBean id="c" class="CustomerBean" > --------------------- <jsp:useBean>The main objective of body is to perform initialization for the newly created bean object, The bean object is already available then it won't be created new bean object it will reuse existing object only , in this case body won't be executed. Attribute list of <jsp:useBean> :
id :
<jsp:useBean id="c" class="CustomerBean" /> // the appropriate equivalent java code CustomerBean c = new CustomerBean(); class :
type :
<jsp:useBean id="p" type="foo.Person" class="foo.Student" /> // equivalent java code foo.Person p = new foo.Student(); scope :
<jsp:useBean id="c" class="CustomerBean" scope="session" /> //equivalent java code CustomerBean c=null; syncronized(session){ c=(CustomerBean)pageContext.getAttribute("c", pageContext.SESSION_SCOPE); if(c==null){ c=new CustomBean(); pageContext.setAttribute("c",c,pageConext.SESSION_SCOPE); ---------------- } }If we specify only type attribute without class attribute then bean object should be already available with in the specified scope if it is not already available then we will get instantiation exception. <jsp:useBean id="c" type="CustomerBean" scope="session" />To use session scope compulsory session object should be available otherwise we will get translation time error. <%@page session="false" %> <jsp:useBean id="c" class="CustomerBean" scope="session" /> exception: Illegal for useBean to use session scope when jsp page declare that it doesn't participate into the session. package foo; public class CalculatorBean { static int i=0; public CalculatorBean(){ System.out.println("calculator bean object created"+ (++i)+"times"); } public int squareIt(int n){ return n*n; } }test.jsp <jsp:useBean id="calc" class="foo.CalculatorBean" scope="session" /> The square of 4 is : <%= calc.squareIt(4) %> The square of 5 is : <%= calc.squareIt(5) %> <a href="beanTest.jsp">Click Here</a>beanTest.jsp <jsp:useBean id="calc" type="foo.CalculatorBean" scope="session" /> The square of 8 is : <%= calc.squareIt(8) %> The square of 9 is : <%= calc.squareIt(9) %>case 2 : <jsp:useBean id="calc" type="foo.CalculatorBean" scope="session" > The square of 8 is : <%= calc.squareIt(8) %> The square of 9 is : <%= calc.squareIt(9) %> </jsp:useBean>case 3 : <jsp:useBean id="c" type="foo.CalculatorBean" scope="session" > The square of 8 is : <%= calc.squareIt(8) %> The square of 9 is : <%= calc.squareIt(9) %> </jsp:useBean>exception: javax.servlet.ServletException:java.lang.InstantiationException person.java package foo; public abstract class Person { public abstract String getMessage(); }Student.java package foo; public class Student extends Person{ public String getMessage(){ return "Ashok"; } public String getName(){ return "Aggidi"; } }test.jsp <jsp:useBean id="p" type="foo.Person" class="foo.Student" scope="session" /> The person name is : <%= p.getMessage() %> <a href="beanTest.jsp">Click Here</a>beanTest.jsp <jsp:useBean id="person" class="foo.Student" scope="session" /> The student name is : <%= person.getName() %> beanName :There may be a chance of using serialized bean object from local file system in that case we have to used beanName attribute.Conclusions for <jsp:useBean> :
package pack1; public class CustomerBean { ----------------- } Assume that no CustomerBean object is already created then which of the following standard actions create a new bean object and store in request scope ?
<jsp:getProperty> :This tag can be used to get the properties of bean object<% CustomerBean c= new CustomerBean(); out.println(c.getName()); %> //equalant jsp <jsp:useBean id="c" class="CustomerBean" /> <jsp:getProperty name="c" property="name" /><jsp:getProperty> tag contains the following 2 attributes
name :It represents name of the bean object reference variable from which the required property has to retrieve , it is exactly equal to id attribute of <jsp:useBean>.property :It represents the name of the java bean property whose value has to retrieve.Note : both attributes are mandatory attributes. package foo; public class CustomerBean{ private String name="ashok"; private String mail="ashok@jobs4times.com"; public String getName() { return name; } public String getMail() { return mail; } }index.jsp <%@page import="foo.CustomerBean" %> <% CustomerBean c=new CustomerBean(); out.println("The customer name is :"+c.getName()); out.println("The customer mail is :"+c.getMail()); %> (OR) <jsp:useBean id="c" class="foo.CustomerBean"/> The Customer name is : <jsp:getProperty property="name" name="c"/> The Customer mail is : <jsp:getProperty property="mail" name="c"/> <jsp:setProperty> :We can use this tag to set the properties of bean object , <jsp:setProperty> tag contains the following forms form 1 :<jsp:setProperty property="age" name="c" value="30" /> (OR) c.setAge("30");form 2 : <jsp:setProperty property="age" name="c" param="age" /> (OR) c.setAge(request.getParameter("age"));Note : The param attribute to retrieve the request parameter value "age" and assign in to java bean property age. form 3 : <jsp:setProperty property="age" name="c" /> (OR) c.setAge(request.getParameter("age"));Note: To get this type of advantage it is highly recommended to maintain bean property names same as form parameter names. form 4 : <jsp:setProperty property="*" name="c" /> // "*" specifies all the properties of java beanNote : It iterates all request parameters and if any request parameter name match with java bean property name then assign request parameter value to the java bean property. <jsp:setProperty> contains the following attributes
name :It represents name of the reference variable of the bean object whose property has to set, this is exactly same as id attribute of <jsp:useBean> , It is mandatory attribute.property :It represents name of the java bean property which has to set, it is mandatory attribute.value :It specifies the value which has to set to the java bean property, it is an optional and should not come combination with param attribute.param :This attribute specifies name of the request parameter whose value has to set to the java bean property, it is an optional attribute and should not come combination with value attribute. CustomerBean.javapackage foo; public class CustomerBean{ private String name=null; private String mail=null; private String age=null; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }index.jsp <form action="test.jsp" method="post"> <h2>Enter Your Details :</h2> Enter Name : <input type="text" name="uname"> Enter Email : <input type="text" name="mail"> Enter Age : <input type="text" name="age"> <input type="submit" value="submit"> </form>test.jsp <h1>Set Property Example : </h1> <jsp:useBean id="c" class="foo.CustomerBean" /> <jsp:setProperty property="*" name="c"/> Entered Name is : <jsp:getProperty property="name" name="c" /> Entered Mail is : <jsp:getProperty property="mail" name="c" /> Entered Age is : <jsp:getProperty property="age" name="c" />Note : All required type conversions(String to int) will be performed automatically by <jsp:setProperty>. Case 1 : test.jsp<h1>Set Property Example : </h1> <jsp:useBean id="c" class="foo.CustomerBean" /> <jsp:setProperty property="mail" name="c" value="<%= request.getParameter("mail") %>" /> //valid <jsp:setProperty property="mail" name="c" value="<%= request.getParameter("age") %>" /> //invalid Entered Name is : <jsp:getProperty property="name" name="c" /> Entered Mail is : <jsp:getProperty property="mail" name="c" /> Entered Age is : <jsp:getProperty property="age" name="c" />Note : Automatic String to primitive conversions doesn't work if we use scripting elements, it fails even if we use expression inside <jsp:setProperty> standard actions. <jsp:useBean id="c" class="foo.CustomerBean" /> <jsp:setProperty property="*" name="c" /> //valid <jsp:setProperty property="empId" name="c" param="empId" /> //valid <jsp:setProperty property="empId" name="c" /> //valid <jsp:setProperty property="empId" name="c" value="1123" /> //validNote : If we are using scripting elements inside jsp standard actions automatic conversions doesn't work but it is possible scripting elements inside standard actions. <jsp:useBean id="c" class="foo.CustomerBean" /> <jsp:setProperty property="empId" name="c" value="<%= request.getParameter("empId") %>" /> //invalid Developing reusable web-components :We can develop reusable web-components by using the following 3 standard actions
<jsp:include> :The response of include page will be included in current response at request processing time, hence it is a dynamic include.This tag representation of pageContext.include("header.jsp"); This standard action contains the following 2 attributes
<jsp:include page="header.jsp" /> <h2>Welcome to Jobs4Times.com</h2> <jsp:include page="footer.jsp" />header.jsp <h2> We are Master in Java Certification </h2>footer.jsp <h4>copyright © www.jobs4times.com </h4> Following 4 possible ways to implement include mechanism in JSP's :
<jsp:forward> :If the first jsp is responsible to perform some preliminary processing activities and second jsp is responsible for providing complete response then we should go for forward mechanism.Syntax : <jsp:forward page="second.jsp" /> It contains only one attribute, i.e., page , and it is a mandatory attribute. first.jsp<h2>This is first Jsp page </h2> <jsp:forward page="second.jsp" /> <h2>This is after forwarding </h2>second.jsp <h2>This is second Jsp page </h2> Following 3 possible ways to implement forward mechanism in JSP's :
<jsp:param> :While forwarding or including if we want to send parameters to the target Jsp we can achieve this by using <jsp:param> tag <jsp:param> tag defines the following 2 mandatory attributes
Note : The parameters which are sending by using <jsp:param> tag are available as form parameters in target Jsp. first.jsp<jsp:include page="second.jsp"> <jsp:param value="ashok" name="username"/> <jsp:param value="25" name="age"/> </jsp:include>second.jsp <%@page isELIgnored="false" %> <h2>Hi i'm getting the values from Jsp param</h2> The UserName is : <%=request.getParameter("username") %> The Age is : <%=request.getParameter("age") %> Conclusions :case 1 :<jsp:forward page="http://localhost:2020/jspApp/second.jsp"/> //invalid <jsp:include page="http://localhost:2020/jspApp/second.jsp"/> //invalid <%@include file="http://localhost:2020/jspApp/second.jsp"%> //invalidThe value of page and file attributes should be a relative path or absolute path but not server port, protocol and etc., case 2 :<jsp:forward page="/test" /> //valid <jsp:include page="/test" /> //valid <%@include file="/test" %> //invalidIn the case of forward and include actions page attribute can pointing to a servlet. But in the case of include directive file attribute can't pointing to a servlet but it can pointing to a Jsp,html,xhtml,xml and etc., case 3 :<jsp:forward page="/test?name=ashok" /> //valid <jsp:forward page="second.jsp?name=ashok" /> //valid <jsp:include page="second.jsp?name=ashok" /> //valid <%@include file="second.jsp?name=ashok" %> //invalidIn the case of include and forward actions we are allowed to pass query string, But in the case of include directive we are not allowed to pass query string. <jsp:plugin> :
<jsp:params> :We can pass any additional parameters to the target applet or bean.<jsp:fallback> :Which specifies any content that should be display to the browser, if the plugin is not started or because of some runtime issues.A plugin specific message will be presented to the end user. A translation time error will occurs if we use <jsp:params> , <jsp:fallback> any other context other than child of <jsp:plugin>. Syntax :<jsp:plugin code="classFileName .class extention" codebase="The directory of class file name" type="applet/bean" > {align="alignment"} {height=""} {width=""} { <jsp:params> { <jsp:param value="pvalue" name="pname"/> } </jsp:params> } <jsp:fallback> Arbitrary test </jsp:fallback> </jsp:plugin> {} ---->optional attributes type :The type of object plugin will execute you must specify either applet or bean, as this attribute there is no default value.It is a mandatory attribute. type="applet/bean" code : (class="ClassFileName")The name of the java class file that plugin will execute we must include .class extension, file name is relative to the directory named in codeBase attribute , it is also mandatory attribute.codeBase : (codeBase="ClassFileDirectoryName")This is a absolute path or relative path to the directory that contains applet code, it is also mandatory attribute. index.jsp<jsp:forward page="plugIn.jsp"></jsp:forward>plugIn.jsp <h2>Welcome to Jsp Application</h2> First Applet : <jsp:plugin code="ClockApplet.class" codebase="applets" type="applet" width="260" height="150"> <jsp:fallback>Plug in tag not supported ..... </jsp:fallback> </jsp:plugin> Second Applet : <jsp:plugin code="edu.com.MessageApplet.class" codebase="applets" type="applet" width="500" height="100"> <jsp:params> <jsp:param value="Welcome to SCWCD" name="msg"/> </jsp:params> <jsp:fallback>No support to this Applet ..... </jsp:fallback> </jsp:plugin>ClockApplet.java public class ClockApplet extends Applet implements Runnable{ String time; public void init(){ Thread t=new Thread(this); t.start(); } public void Paint(Graphics g){ g.setColor(Color.lightGray); g.fill3DRect(40, 40, 150, 100, true); g.setFont(new Font("monotypeCorsiva",Font.ITALIC,35)); g.setColor(Color.red); g.drawString(time, 60, 100); } public void run() { while(true){ time=String.valueOf( new SimpleDateFormat("hh:mm:ss").format(new Date())); repaint(); try{ Thread.sleep(1000); }catch (InterruptedException e) { e.printStackTrace(); } }//run } }//classMessageApplet.java package edu.com; public class MessageApplet extends Applet implements Runnable{ String message; public void init(){ message=getParameter("msg");//available in applet class if(message==null){ message="This is default message"; } } public void Paint(Graphics g){ g.setColor(Color.BLUE); g.setFont(new Font("monotype Corsiva",Font.ITALIC,40)); g.drawString(message, 20, 50); } public void run() { } }first.jsp <h2>This is first Jsp Page</h2> <%! String nextPage="second.jsp"; %> <jsp:forward page="<%= nextPage %>" /> //valid // static or dynamic <h2>This is after forwarding</h2>second.jsp <h2>This is second Jsp Page</h2> Summary of Standard actions :
JSP Documentation :They are 2 types syntaxes are possible to write a Jsp
directives :
<jsp:root xmlns:mime="www.jobs4times.com" version="4.3" /> //version is mandatory attribute //xmlns:mime is an optional attribute //and we can take any no.of xml name spaces Standard actions :There is no difference in standard actions representation between standard syntax and xml based syntax.Ex :
Comments :Jsp specification doesn't provide any specific syntax for writing comments , hence we can use normal syntax
Template text :Jsp Standard syntax doesn't provide any specific way to write template text but Xml based syntax it provides a special tag <jsp:text>
How the web-container identifies Jsp document ?
Write a Jsp document to print hit count of the Jsp ?index.jsp (servlet 2.5v)<jsp:directive.page isELIgnored="false" /> <!-- including header.jsp to current jsp --> <jsp:directive.include file="header.jsp" /> <jsp:declaration> int count=0; </jsp:declaration> <jsp:scriptlet> count++; </jsp:scriptlet> <jsp:text>The hit count of this page is : </jsp:text> <jsp:expression> count </jsp:expression>
Which of the following valid way of importing java.util.ArrayList in our Jsp ?<jsp:page import="java.util.ArrayList" /> //invalid <jsp:page.directive import="java.util.ArrayList" /> //invalid <jsp:directive page import="java.util.ArrayList" /> //invalid <jsp:directive.page import="java.util.ArrayList" /> //valid Person.java package foo; public class Person { private String name; private Dog dog; public String getName() { return name; } public void setName(String name) { this.name = name; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } }Dog.java package foo; public class Dog { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }JspDemoServlet.java public class JspDemoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { foo.Person p=new Person(); p.setName("ashok"); foo.Dog d=new Dog(); d.setName("spike"); p.setDog(d); request.setAttribute("person", p); RequestDispatcher rd=request.getRequestDispatcher("view.jsp"); rd.forward(request, response); } }view.jsp The Person's Dog name is : <%=((foo.Person)request.getAttribute("person")).getDog().getName()%>It is never recommended to use Scripting elements in Jsp , hence the above solution is not proper approach <jsp:useBean id="person" class="foo.Person" scope="request" /> The Person's Dog name is : <jsp:getProperty property="dog" name="person" /> output: The Person's Dog name is : foo.Dog@1234... //If request scope is not specified the output is nullSolution : ${Person.dog.name} The <Jsp:getProperty> tag lets you access only property of bean attributes, there is no capability for nested properties, where you want a property of property rather than property of attribute. Limitations of Standard Actions :Standard Actions can handle String and primitive properties , if we know the standard actions can deal with in a attribute of any type as long as all the attribute properties are String/primitives.there is no capability for nested properties. |