JSP Advance (Part-II)

Discussion in 'JSP' started by techgeek.in, Apr 15, 2010.

  1. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
    http://www.techgeek.in
    In the previous article I explained about the different JSP tags except action tags. In this article I have explained about the JSP implicit objects and JSP action tags in details.

    JSP Implicit Objects



    JSP provides a set of implicit objects that can be used to access many server-side objects that represent the incoming request, response, and session objects. These objects are actually defined in the _JSP pageservice() method of the page implementation class and initialized with appropriate references.

    JSP defines four scopes for the objects that can be used by the JSP authors:

    Scope --------> Description
    page ---------> Objects can be accessed only within the JSP page in which they are referenced.
    request ------> Objects can be accessed within all the pages that serve the current request. These include pages that are forwarded to, and included in, the original JSP page to which the request was routed.
    session ------> Objects can only be accessed within the JSP pages accessed within the session for which the objects are defined.
    application --> Application scope objects can be accessed by all JSP pages in a given context.

    The following relation lists the implicit objects that can be used in scriptlets:-

    request Object is Protocol dependent sub type of javax.servlet.ServletRequest with request scope - A reference to the current request.
    response Object is Protocol dependent sub type of javax.servlet.ServletResponse with page scope - The response to the request.
    pageContext Object is javax.servlet.jsp.PageContext type with page scope - Provides a common point to access the request, response, session, and application, associated with the page being served.
    session Object is javax.servlet.http.HttpSession type with session scope - The session associated with the current request.
    application Object is javax.servlet.ServletContext type with application scope - The servlet context to which the page belongs.
    out Object is javax.servlet.jsp.JspWriter type with page scope - The object that writes to the response output stream.
    config Object is javax.servlet.ServletConfig type with page scope - The servlet configuration for the current page.
    Page Object is java.lang.Object type with page scope - An instance of the page implementation class that is serving the request (synonymous with the this keyword if Java is used as the scripting language).
    exception Object is java.lang.Throwable type with page scope - Available with JSP pages that act as error pages for other JSP pages.

    The following JSP page illustrates the use of implicit objects in JSP pages. Save this as webapps/jsp/Implicit.jsp:-

    Code:
        <html>
          <head>
            <title>Implicit Objects</title>
          </head>
          <body style="font-family:verdana;font-size:10pt">
            <p>
              Using Request parameters...<br>
    
    //We print the request parameter name:
    
                Using Request parameters...<br>
                Name: <%= request.getParameter("name") %>
              </p>
    
    //We print a sentence using the out implicit variable:
    
              <p>
                <% out.println("This is printed using the out implicit variable"); %>
              </p>
    
    //We store and retrieve an object of type String using the session implicit variable:
    
              <p>
              Storing a string to the session...<br>
              <% session.setAttribute("name", "harsh"); %>
              Retrieving the string from session...<br>
              <b>Name:</b> <%= session.getAttribute("name") %>
            </p>
    
    //Store and retrieve an object of type String in the servlet context using the application implicit variable:
    
            <p>
              Storing a string to the application...<br>
              <% application.setAttribute("name", "harsh"); %>
              Retrieving the string from application...<br>
              <b>Name:</b> <%= application.getAttribute("name") %>
            </p>
    
    //Finally, store and retrieve an object of type String in the page context using the pageContext implicit variable:
    
            <p>
              Storing a string to the page context...<br>
              <% pageContext.setAttribute("name", "harsh"); %>
              Retrieving the string from page context...</br>
              <b>Name:</b> <%= pageContext.getAttribute("name") %>
            </p>
         </body>
       </html>
    
    Access this JSP page at http://localhost:8080/jsp/Implicit.jsp?name=harsh and you will see:-

    [​IMG]

    JSP Actions



    JSP actions are processed during the request processing phase (as opposed to directives, which are processed during the translation phase). The JSP specification defines a few standard actions that must be supported by all compliant web containers. JSP also provides a powerful framework for developing custom actions, which are included in a JSP page using the taglib directive.

    1) The jsp:include Action:- The JSP specification defines the include action for including static and dynamic resources in a JSP page. With the include directive the contents of the included resource is substituted into the JSP page at translation phase but with the include action the response of the included resource is added to the current response output stream during the request processing phase.

    The following code shows how we can use the include action:

    Code:
    <jsp:include page="includedPage.jsp" flush=”true” />
    The attributes of this action are:-
    Page= The resource to include.
    Flush= this is optional with the default value of false. If the value is true the buffer in the output Stream is flushed before the inclusion is performed.

    This action will include the output of processing includedPage.jsp within the output of the JSP page during the request processing phase.
    There are some important points to note regarding the include action and directive:
    Changing the content of the included resource used in the include action is automatically reflected the next time the including JSP is accessed. The include directive is normally used for including both dynamic and static resources, the include action is used for including only dynamic resources.

    Consider the Following example:
    Webapps\jsp\includeAction.jsp
    Code:
    <html>
    <head>
    <title>
    Include Action Test Page
    </title>
    </head>
    <body>
    <h1>Include Action Test Page</h1>
    <h2>Using the include directive</h2>
    <%@ include file="include2.html" %>
    <%@ include file="include2.jsp" %>
    <h2>Using the include action</h2>
    <jsp:include page="include2.html" flush="true" />
    <jsp:include page="include2.jsp" flush="true" />
    </body>
    </html>
    
    include2.html
    Code:
    <html>
    <head>
    <title>Included HTML</title>
    </head>
    <body>
    This is some static text in the included HTML file
    </body>
    </html>
    
    include2.jsp
    Code:
    <html>
    <head>
    <title>Included JSP</title>
    </head>
    <body>
     <h3>
              The date is
              <% out.println((new java.util.Date()).toString()); %>
            </h3>
            </body>
    </html>
    
    
    [​IMG]

    1) The jsp:forward Action:- The JSP specification defines the forward action to be used for forwarding the response to other web application resources. The forward action is the same as forwarding to resources using the RequestDispatcher interface.
    The following code shows how to use the forward action:

    Code:
    <jsp:forward page="Forwarded.html"/> 
    This action will forward the request to Forwarded.html.
    We can only forward to a resource if content is not committed to the response output stream from the current JSP page. If content is already committed, an IllegalStateException will be thrown. To avoid this we can set a high buffer size for the forwarding JSP page.

    Forward.html
    Code:
    <html>
    <head>
    <title>Forward Action Test Page</title>
    </head>
    <body>
    <h1>Forward Action Test Page</h1>
    <form method="post" action="forward.jsp">
    <p>Please enter your username:
    <input type="text" name="username">
    <br> and passowrd:
    <input type="password" name="password">
    </p>
    <p><input type="submit" value="Log In">
    </form>
    </body>
    </html>
    
    Forward.jsp
    Code:
    html>
    <head>
    <title>Forwarded JSP</title>
    </head>
    <body>
    <%
    if ((request.getParameter("username").equals("Admin")) && 
    		(request.getParameter("password").equals("Admin"))){
    		
    %>
    <jsp:forward page="forward2.jsp" />
    <%
    }
    else
    {
    %>
    <%@ include file="forward.html" %>
    <%
    }
    %>
    </body>
    </html>
    
    Forward2.jsp
    Code:
    <html>
    <head>
    <title> Forward action test: Login Successful</title>
    </head>
    <body>
    <h1>Forward action test: Login Successful</h1>
    <p> Welcome , <%= request.getParameter("username") %></p>
    </body>
    </html>
    
    Start Tomcat and go to http://localhost:8080/jsp/forward.html

    Then login with username=Admin and password=Admin

    [​IMG]

    [​IMG]

    3) The jsp: param Action:-

    The JSP param action can be used in conjunction with the include and forward actions to pass additional request parameters to the included or forwarded resource. The param tag needs to be embedded in the body of the include or forward tag.

    The following code shows how we can use the param action:

    Code:
    <jsp:forward page="Param2.jsp">
       <jsp: param name="name" value="Techgeek"/>
    </jsp:forward>
    
    In addition to the request parameters already available, the forwarded resource will have an extra request parameter named name, with a value of Techgeek.

    Using JavaBeans with JSP Pages



    The JSP specification defines a powerful standard action that helps to separate presentation and content by allowing page authors to interact with JavaBean components that are stored as page, request, session and application attributes. The useBean tag along with the getProperty and setProperty tags allows JSP pages to interact with JavaBean components.

    4) The jsp:useBean Action:-

    The useBean action creates or finds a Java object in a specified scope. The object is also made available in the current JSP page as a scripting variable. The syntax for the useBean action is:

    Code:
    <jsp:useBean id="name" scope="page | request | session | application"
    	class="className" type="typeName" |
    	bean="beanName" type="typeName" |
    	type="typeName" />
    
    At least one of the type and class attributes must be present, and we can't specify values for both the class and bean name. The useBean JSP tag works according to the following sequence:

    First, the container tries to find an object by the specified name in the specified scope.

    If an object is found, a scripting variable is introduced with the name specified by the id attribute and type specified by the type attribute. If the type attribute is not specified the value of the class attribute is used. The variables value is initialized to the reference to the object that is found. The body of the tag is then ignored.

    If the object is not found and both class and beanName are not present, an InstantiationException is thrown.

    If the class defines a non-abstract class with public no-argument constructor an object of that class is instantiated and stored in the specified scope using the specified ID. A scripting variable is introduced with the name specified by the id attribute and type specified by the class attribute. If the value of the class attribute specifies an interface, a non-public class or a class without a public no-argument constructor, an InstantiationException is thrown. The body of useBean of the tag is then executed.

    If the beanName attribute is used then the java.beans.Bean.instantiate() method is called, passing the value of the attribute beanName. A scripting variable is introduced with the name specified by the id attribute and type specified by the type attribute. The body useBean of the tag is then executed.

    For example:
    Code:
        <jsp:useBean id="myName" class="java.lang.String" scope="request">
        </jsp:useBean>
    

    5) The jsp:getProperty Action:-


    The getProperty action can be used in conjunction with the useBean action to get the value of the properties of the bean defined by the useBean action. For example:

    Code:
    <jsp:getProperty name="myBean" property="firstName"/>
    The name attribute refers to the id attribute specified in the useBean action. The property attribute refers to the name of the bean property. In this case the bean class should have a method called getFirstName() that returns a Java primitive or object.

    6) The jsp:setProperty Action:-


    The setProperty action can be used in conjunction with the useBean action to set the properties of a bean. We can even get the container to populate the bean properties from the request parameters without specifying the property names. In such cases the container will match the bean property names with the request parameter names. The syntax for the setProperty action is shown below:

    Code:
    <jsp:setProperty name="beanName"
    	property="*" |
    	property="propertyName" |
    	property="propertyName" param="paramName" |
    	property="propertyName" value="value" />
    
    To set the value of the name property of myBean to harsh we would use:

    Code:
    <jsp:setProperty name="myBean" property="name" value="harsh"/>
    To set the value of the name1 property of myBean to the value of the request parameter name2 we would use:

    Code:
    <jsp:setProperty name="myBean" property="name1" param="name2"/>
    To set the value of the name property of myBean to the value of the request parameter by the same name we would use:

    Code:
     <jsp:setProperty name="myBean" property="name1"/>
    Finally, to set all the properties of myBean with matching request parameters from the request parameter values we would use:

    Code:
    <jsp:setProperty name="myBean" property="*"/>
    The following is an example illustrating the useBean ,getProperty and setPreoperty action tags.

    Webapps\jsp\beans.html


    Code:
    <html>
    <head>
    <title>useBean Action Test Page</title>
    </head>
    <body>
    	<h1>useBean Action Test Page</h1>
    	<form method="post" action="beans.jsp">
    		<p>
    			Please enter your username:
    				<input type="text" name="name">
    				<br> What is your favourite programming language?
    			<select name="language">
    				<option value="Java">Java</option>
    				<option value="C++">C++</option>
    				<option value="Perl">Perl</option>
    				<option value="C">C</option>
    			</select>
    		</p>
    		<input type="submit" value="Submit Information">
    	</form>
    </body>
    </html>
    
    
    webapps\jsp\beans.jsp
    Code:
    <html>
    <head>
    <title>useBean Action Test Page</title>
    </head>
    <body>
    	<h1>useBean Action Test Page</h1>
    	<form method="post" action="beans.jsp">
    		<p>Please enter your username:
    			<input type="text" name="name">
    			<br> What is your favourite programming language?
    			<select name="language">
    				<option value="Java">Java</option>
    				<option value="C++">C++</option>
    				<option value="Perl">Perl</option>
    				<option value="C">C</option>
    			</select>
    		</p>
    		<input type="submit" value="Submit Information">
    	</form>
    </body>
    </html>
    

    webapps\jsp\com\LanguageBean.class

    Code:
    package com;
    
    public class LanguageBean {
    	private String name;
    	private String language;
    	
    	public LanguageBean(){
    
    }
    	public void setName(String name){
    		this.name=name;
    	}
    	public String getName()
    	{
    		return name;
    		
    	}
    	public void setLanguage(String language){
    		this.language=language;
    	}
    	public String getLanguage()
    	{
    		return language;
    		
    	}
    }
    
    [​IMG]

    [​IMG]

    6) The jsp: plugin Action:-

    The plugin action enables the JSP container to render appropriate HTML to initiate the download of the Java plugin and the execution of the specified applet or bean, depending on the browser type. The plugin standard action allows us to embed applets and beans in a browser-neutral manner as the container takes care of the user agent specific issues. For example:

    Code:
    <jsp: plugin type="applet" code="MyApplet.class" codebase="/">
       <jsp: params>
    	  <jsp: param name="myParam" value="123"/>
       </jsp: params>
       <jsp:fallback><b>Unable to load applet</b></jsp:fallback>
    </jsp: plugin>
    
    The params and param tag are used to define applet parameters. The fallback tag can be used to define any HTML markup that needs to be rendered upon failure to start the plugin.
     
    Last edited by a moderator: Jan 21, 2017
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  4. iamscottj

    iamscottj New Member

    Joined:
    Aug 18, 2010
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    US
    Interesting article and I think it has covered most of the important intrinsic objects which are definitely required every time. I was quite confused while my time of learning about the "include" tag. Now I got that its actually useful if we want to emulate like master pages in ASP.NET. I am actually an ASP.NET fan and I learned JSP just to know other technology. Small suggestion is that please capture good screen-shots at proper resolution to avoid the blurs and stretching.
     
  5. TPrice

    TPrice New Member

    Joined:
    Aug 24, 2010
    Messages:
    9
    Likes Received:
    1
    Trophy Points:
    0
    Thank you very much for this very informative post. I am a newbie and appreciate all of the great information on this forum. I think this forum is an ideal resource for someone like me who is learning the ropes. This particular thread has answered some questions that I had and I am very grateful. I have lots more to learn, and expect to be digging through the goldmine of information here.
     
  6. tiwvinay

    tiwvinay New Member

    Joined:
    May 7, 2011
    Messages:
    18
    Likes Received:
    0
    Trophy Points:
    0
    thanks for information in jsp advance
     
  7. Tobiasgar

    Tobiasgar New Member

    Joined:
    Aug 29, 2011
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.mspy.com
    Before reading the thread the topic of JSP seemed something horrable :crazy: for me, but now i see that it's not so complicated as it seemed !! Thanks
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice