Chapter 2



JSP Element



              http://www.java2all.com
JSP Element



              http://www.java2all.com
In previous example described in introduction
  to JSP, We didn`t use any java statement or code in
  the file. If the developer wants to put any java code
  in that file then the developer can put it by the use
  of jsp tags(elements).

      There are mainly three group of jsp
  tags(elements) available in java server page :
1 ) JSP Scripting elements
2 ) JSP Directive elements
3 ) JSP Standard Action elements
  All three elements described in next three topic.
                                             http://www.java2all.com
JSP Scripting elements



                    http://www.java2all.com
1. JSP Scripting elements :

     There are four types of tag in jsp scripting
elements.

a) JSP Declaration tag.

b) JSP scriptlet tag.

c) JSP Expression tag.

d) Comment tag.

Now we describe each tag in detail.           http://www.java2all.com
a) JSP Declaration tag :

  A JSP declaration lets you declare or define
  variables and methods (fields) that use into the jsp
  page.

  Declaration tag Start with <%! And End with
  %>
  The Code placed inside this tag must end with a
  semicolon (;).

Syntax:   <%! Java Code; %>

                                             http://www.java2all.com
<%! private int i = 10; %>
   <%! private int squre(int i)
   {
       i=i*i;
       return i;
   }
%>


     You can also put these codes in a single syntax
block of declaration like,
 <%! private int i = 10;
      private int squre(int i)
  {
          i=i*i;
          return i;
      }
%>

     Note : The XML authors can use an alternative
syntax for JSP declaration tag:
                                            http://www.java2all.com
<jsp:declaration>
    Java code;
</jsp:declaration>

EX.
<jsp:declaration> private int i = 1; </jsp:declaration>
 <jsp:declaration>
  {
            private int squre(int i)
            i=i*i;
            return i;
  }
</jsp:declaration>

       You can also put these codes in a single syntax block of
declaration like,
<jsp:declaration>
    private int i = 1;
  private int squre(int i)
  {
     i=i*i;
      return i;
  }
</jsp:declaration>
                                                           http://www.java2all.com
Remember that XML elements, unlike HTML
ones, are case sensitive. So be sure to use lowercase.

     Declarations do not generate any output so the
developer uses declaration tag with JSP expression tag
or JSP scriptlet tag for generating an appropriate
output for display it in the appropriate browser.




                                              http://www.java2all.com
b) JSP scriptlet tag :

      A JSP scriptlet lets you declare or define any
java code that use into the jsp page.

     scriptlet tag Start with <% and End with
%>

     The Code placed inside this tag must end
with a semicolon (;).

     Syntax:    <% Java Code; %>

                                              http://www.java2all.com
EX.
<%
            int a = 10;
            out.print("a ="+a);
%>


Note :      The XML authors can use an alternative
syntax for JSP scriptlet tag.
<jsp:scriptlet>
   Java code;
</jsp:scriptlet>




                                           http://www.java2all.com
c) JSP Expression tag :

       A JSP expression is used to insert Java values directly
into the output.

      JSP Expression tag is use for evaluating any expression
and directly displays the output in appropriate web browser.

      Expression tag Start with <%= and End with %>

     The Code placed inside this tag not end with a
semicolon (;).

      Syntax:    <%= Java Code %>

                                                    http://www.java2all.com
For example. the following shows the date/time
that the page was requested:

     Current time: <%= new java.util.Date() %>

     Note : The XML authors can use an alternative
syntax for JSP expressions:

<jsp:expression>
      Java Expression
</jsp:expression>


                                           http://www.java2all.com
d) Comment tag :

       Although you can always include HTML
comments in JSP pages, users can view these if they
view the page's source. If you don't want users to be
able to see your comments, embed them within the <
%-- ... --%> tag.
 <html>
 <head>
    <title>Comment demo</title>
 </head>
 <body>
  <p>This is simple demo of test the comment </p>
    <!-- This is a comment. Comments are not displayed in the browser but displayed in view source -->
<%-- This is a comment. Comments are not displayed in the browser as well as not displayed in view
source also --%>
 </body>
</html>
                                                                                     http://www.java2all.com
Output :
    This is simple demo of test the comment.

     Now right click on the browser and select the
view source so we can get the code in Notepad like,
<html>
 <head>
   <title>Comment demo page</title>
 </head>
 <body>
  <p>This is simple demo of test the comment. </p>
    <!-- This is a comment. Comments are not displayed in the browser but displayed in view source -->
 </body>
</html>

     In the view sorce code, the comment put in <%--
comment --%> will not display but the comment put
in <!—comment will display.
                                                                                   http://www.java2all.com
Now using these JSP Scripting elements, we are developing some
simple examples so the use of these tags can easily understood.
<html>
 <head>
    <title>Scripting Demo page</title>
 </head>
 <body>
  <%-- declaration tag --%>
  <%! int i = 10; %>

  <%-- scriptlet tag --%>
  <% out.print("i = "+i); %>
  <br>
  <br>
  <% out.print("for loop execution start..........."); %>
  <br>
  <%
  for(int j=1;j<=10;j++)
  {
    out.print("j = "+j);
  %>
  <br>
  <%
  }
                                                            http://www.java2all.com
out.print("for loop execution complete...........");
 %>
 <br>
 <br>

  <%-- expression tag --%>
  <%! int a = 10;
    int b = 20;
  %>
  The addition of two variable : a + b = 10 + 20 = <%= a+b %>
  <br>
  <br>
  Current time : <%= new java.util.Date() %>
 </body>
</html




                                                                http://www.java2all.com
Output :
 i = 10
for loop execution start...........
j=1
j=2
j=3
j=4
j=5
j=6
j=7
j=8
j=9
j = 10
for loop execution complete...........
 The addition of two variable : a + b = 10 + 20 = 30
 Current time : Sun Feb 12 14:00:35 IST 2012

                                                       http://www.java2all.com
JSP Directive elements



                   http://www.java2all.com
2. JSP Directive elements :

     A JSP directive gives special information about
the page to JSP Engine.

     Each JSP goes through two phases:

(1) The first phase is known as translation time,
during which the JSP engine turns the file into
a servlet. (The step following from 1 to 5 in JSP
Architecture)

                                            http://www.java2all.com
•     The second phase is known as request time,
    during which the resulting servlet is run to
    actually generate the page. (The step following
    from 6 to 9 in JSP Architecture)

  The JSP engine handles the directives at translation
  time because the JSP engine will translate a
  particular directive into a servlet only for the first
  time so the developer can get more speed for the
  process of loading a JSP file in a future.
Syntax:

    <%@ directive-name [attribute=”value”
    attribute=”value”………….] %>                http://www.java2all.com
Note : The XML syntax for defining directives
is
<jsp:directive.directiveType [attribute=”value”
attribute=”value”………….] /> Three main types of
directives are:

a)   page directive

b)   include directive

c)   taglib directive

                                          http://www.java2all.com
a) page directive :

   The page directive is used to specify attributes
   for the JSP page as a whole.

   The page directive does not produce any
   visible output when the page is requested but
   change the way the JSP Engine processes the
   page.

   e.g., you can make session data unavailable to
   a page by setting a session to FALSE.

                                              http://www.java2all.com
Syntax:

      <@ page [attribute=”value”
attribute=”value”………….] %>

      The table given below describes the possible
attributes for the page directive.




                                            http://www.java2all.com
Syntax
Attribute          Description           (default value is      Example
                                             in bold)
            This tells the server about
             the language to be used                            <%@ page
language     in the JSP file. Presently language="java"      language="java"
              the only valid value for                             %>
               this attribute is java.
            This attribute defines the   import="packag     <%@ page
 Import       list of packages, each        e.class"    import="java.util.
             separated by comma .                        *, java.io.*"%>
             Indicates the superclass                      <%@ page
                                         extends="packa
Extends         of servlet when jsp                     extends="com.Co
                                            ge.class"
               translated in servlet.                       nnect"%>



                                                                http://www.java2all.com
true indicates session
               should be bound to the
                existing session if one
               exists, otherwise a new     session="true|       <%@ page
  Session
             session should be created          false"       session="true"%>
              and bound to it and false
             indicates that no sessions
                     will be used.
              specifies the buffer size    buffer="sizekb|     <%@ page
   Buffer
             for out and default is 8kb.        none"        buffer="8kb"%>
                   True indicates
             multithreading and false                       <%@ page
                                        isThreadSafe="tr
isThreadSafe indicates that the servlet                  isThreadSafe="tr
                                            ue|false"
                 should implement                             ue"%>
                SingleThreadModel



                                                               http://www.java2all.com
true indicates that the
             buffer should be flushed
              when it is full and false
                                        autoflush="tru     <%@ page
 autoFlush    indicates indicates that
                                           e|false"    autoFlush="true"%>
              an exception should be
             thrown when the buffer
                     overflows.
                                                            <%@ page
             This defines a string that               info="This is a simple
                                        info="message
   Info      can be retrieved via the                   jsp file created by
                                              "
              getServletInfo method.                   Java2all team on 22
                                                           Feb 2011"%>
                                                        <%@ page
pageEncodin This defines data type of pageEncoding=
                                                    pageEncoding="ISO-
     g           page encoding.        "ISO-8859-1"
                                                        8859-1"%>
contentType This specifies the MIME contentType="      <%@ page
              type of the output.    MIME-Type" contentType="text/h
                                                          tml;
                                                  charset=ISO-8859-1"
                                                             http://www.java2all.com
<%@ page
                This defines       isELIgnored="
isELIgnored                                         isELIgnored="false
              ENUM data type.       true|false "
                                                           "%>

                This indicates
               whether or not                           <%@ page
                                  isErrorPage="true
isErrorPage   the current page                      isErrorPage="false
                                        |false"
                can act as the                             "%>
                 error page.
              Define a URL to
              another JSP that
               is invoked if an                         <%@ page
errorPage         unchecked       errorPage="url"   errorPage="error.j
                    runtime                               sp"%>
                 exception is
                    thrown.

                                                        http://www.java2all.com
<%@   page language="java"
      import="java.util.*,java.io.*"
      extends="com.Connect"
      autoFlush="true"
      errorPage="error.jsp"
      info="This is a simple jsp file created by Java2all team on 22 Feb 2011"
      isELIgnored="false"
      isErrorPage="false"
      session="true"
      buffer="8kb"
      contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"
      isThreadSafe="true"
%>


NOTE :
                The XML equivalent of

<%@ page import="java.util.*" %> is
<jsp:directive.page import="java.util.*" />

                                                                                 http://www.java2all.com
b) include directive :

      It allows a JSP developer to include source code
(static resource) of a file inside jsp file at the
specified place at a translation time.

      Typically include files are used for headers,
footers, tables and navigation that are common to
multiple pages.

     The included page should not be another
dynamic page so the included file does not need to be
a complete and valid JSP or servlet.
                                              http://www.java2all.com
Syntax:
<%@ include file="/folder_name/file_name"%>

      If the included file and JSP file are available in
the same folder then the folder name is not required in
syntax.

     <%@ include file="file_name"%>

      Now we are describe the include directive by
one simple example so the use of include directive in
JSP file is easily understand.
                                              http://www.java2all.com
Step-1 :               Create two folder in webRoot
                       (i) HTMLFILE and (ii) JSPFILE.

Step-2 :              Create a new HTML file(Included.html) in
                      HTMLFILE folder.

Step-3 :              Replace the source code of a
                      file(Included.html) by the below code.
<html>
 <head>
  <title> Included.html </title>
 </head>

 <body>
  <b>This is HTML page which is include in JSP file by using directive include tag in JSP file.</b> <br>
 </body>
</html>

                                                                                          http://www.java2all.com
Step-4 :             Create a jsp file(IncludeDemo.jsp) in
                     JSPFILE folder.
Step-5 :             Now replace the source code of a
                     file(IncludeDemo.jsp) by the below code.
<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>

  <title> IncludeDemo.jsp </title>
 </head>

 <body>
  This is a JSP page. <br>
<%@ include file="/HTMLFILE/“Included.html"%>
 </body>
</html>




                                                                                 http://www.java2all.com
Step-6 :   Now Redeploy the Project and start the
           Server.
Step-7 :   Enter the appropriate URL in web-
           browser.




                                           http://www.java2all.com
Output :

    This is a JSP page.
    This is HTML page which is include in jsp file
    by using directive include tag in jsp file.




                                          http://www.java2all.com
c) taglib directive :

      The taglib directive makes custom actions
available in current page through the use of tag
library.

Syntax:
<%@ taglib uri="tag Library_path"
prefix="tag_prefix"%>

uri ====> The absolute path (URL) of a Tag Library
Descriptor.
prefix ====> A unique prefix used to identify custom
tags from library used later in the JSP page. http://www.java2all.com
EX.

<%@ taglib uri="/tlds/TableGenerator.tld"
prefix="tg"%>

      And if TableGenerator.tld defines a tag named
table, then the JSP file can contain tag of following
type:
<tg:table>
……….
……….
</tg:table>
NOTE : We discuss taglib directory in detail in
further chapter.                                http://www.java2all.com
JSP Standard Action elements



                      http://www.java2all.com
JSP Standard Action elements:

     Actions are high-level JSP elements that create,
modify or use other objects.

     Unlike directives and scripting elements, JSP are
coded using strict XML syntax form.

     By the use of JSP actions elements you can
dynamically insert a file, reuse JavaBeans
components, forward the user to another page, or
generate HTML for the Java plugin etc.
                                            http://www.java2all.com
The standard action types are:

(1)   <jsp:param>
(2)   <jsp:include>
(3)   <jsp:forward>
(4)   <jsp:fallback>
(5)   <jsp:plugin>
(6)   <jsp:useBean>
(7)   <jsp:setProperty>
(8)   <jsp:getProperty>
                                 http://www.java2all.com
(1)   <jsp:param>

     The <jsp:param> action is used to provide other
tags with additional information in the form of name
value pairs.

      This action is used in conjunction with
jsp:include, jsp:forward and jsp:plugin actions.

Syntax :
<jsp:param name=”parameter_name”
value=”parameter_value” />
                                             http://www.java2all.com
OR
 <jsp:param name=”parameter_name”
 value=”parameter_value”>
 </ jsp:param>

  For Example,
<jsp:param name=”font_size” value=”20” />

OR

<jsp:param name=”font_size” value=”20”>
  </jsp:param >
                                          http://www.java2all.com
(2)   <jsp:include>

      This action allows a static or dynamic resource
to be including in the JSP at request time.

      If page is buffered then the buffer is flushed
prior to the inclusion.

Syntax :

<jsp:include page= “file_name” flush = “true|false”
/>

                                               http://www.java2all.com
OR
<jsp:include page= “file_name” flush = “true|false” >
<jsp:param name=”parameter_name”
  value=”parameter_value” />
</jsp:include >

NOTE :
     A <jsp:include> action may have one or more
 <jsp:param> tags in its body, to provide additional
 name-value pairs.


                                            http://www.java2all.com
Included.jsp :-
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
  <title>Included.jsp</title>
 </head>
 <body>
 This is the message of Included.jsp file..............<br>
 </body>
</html>

Include.jsp :-
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
  <title>Include.jsp</title>
 </head>
 <body>
 This is the message of Include.jsp file..............<br>
 <jsp:include page="Included.jsp" />
 </body>
</html>
                                                                            http://www.java2all.com
Now run the Included.jsp in the appropriate
  browser so you can get the below output in the
  browser,

Output:
    This is the message of Include.jsp file..............
    This is the message of Included.jsp file..............

Example-2 :
      Write a simple program which demonstrate the
  use of <jsp:param> in <jsp:include> action element.

                                                 http://www.java2all.com
Employee.jsp :-

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
  <title>Employee.jsp</title>
 </head>
 <body>
 <b><i><% out.print("Name : "+request.getParameter("name1")); %></i></b> <br>
 <% out.print("He is a "+request.getParameter("profile1")+" dept. in Noble Engineering College -
    Junagadh."); %> <br>
 <b><i><% out.print("Name : "+request.getParameter("name2"));%></i></b><br>
 <% out.print("He is a "+request.getParameter("profile2")+" dept. in Noble Engineering College -
    Junagadh."); %>
 </body>
</html>




                                                                                     http://www.java2all.com
Information.jsp :-

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
 <title>Information.jsp</title>
 </head>
 <body>
 <jsp:include page="Employee.jsp">

 <jsp:param value="Prof. Ashutosh A. Abhangi" name="name1"/>
 <jsp:param value="H.O.D. of Info. Tech. " name="profile1"/>

 <jsp:param value="Prof. Kamal N. Kotecha" name="name2"/>
 <jsp:param value="H.O.D. of C.S.E. " name="profile2"/>

 </jsp:include>
 </body>
</html>


                                                                            http://www.java2all.com
Now run the Information.jsp in the appropriate
  browser so you can get the below output in the
  browser,

Output:
 Name : Prof. Ashutosh A. Abhangi
 He is a H.O.D. of Info. Tech. dept. in Noble
 Engineering College - Junagadh.
 Name : Prof. Kamal N. Kotecha
 He is a H.O.D. of C.S.E. dept. in Noble Engineering
 College - Junagadh.

                                            http://www.java2all.com
NOTE : Difference between Directive include
and Action include element.

                                        Included
Include       Syntax       Done when                     Parsing
                                        Content


            <%@include
            file=”file_na Compilation
Directive                                Static       Container
               me”%>         time



            <jsp:include    Request                  Not parsed
                                        Static or
 Action     page=”file_n   Processing               but included
                                        dynamic
              ame”%>          time                  in container
                                                    http://www.java2all.com
(3)  <jsp:forward>
     With the forward action, the current page stops
  processing the request and forwards the request to
  another page.
     Execution never returns to the calling (current)
  page.
Syntax :
<jsp:forward page= “file_name” />
OR
<jsp: forward page= “file_name”>
<jsp:param name=”parameter_name”
   value=”parameter_value” />
</jsp: forward>                            http://www.java2all.com
The meaning as well as use of the attributes and
  the <jsp:param> element are same as for
  <jsp:Include> action element.
Example-1 :
      Write a simple program which demonstrate the
  <jsp:forward> action element.
Current.jsp :
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
 <title>Current.jsp</title>
 </head>
 <body>
  This is a Current page
  <jsp:forward page="Forward.jsp" />
 </body>
</html>
                                                                            http://www.java2all.com
Forward.jsp :
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
 <title>Forward.jsp</title>
 </head>
 <body>
  Welcome, Forward is working now and this is a Forwarded page...............<br/>
 </body>
</html>

    Now run the Current.jsp in the appropriate
 browser so you can get the below output in the
 browser,
Output:
    Welcome, Forward is working now and this is a
 Forwarded page...............
                                                                                     http://www.java2all.com
Example-2 :
      Write a simple Login Application by using
  <jsp:forward> action element.
Login.jsp :
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
 <title>Login.jsp</title>
 </head>
 <body>
  <form action="Check.jsp">
    User Name : <input type="text" name="name"> <br>
    Password : <input type="text" name="password"> <br>
    <input type="submit" value="Sign in">
    <input type="reset" value="Reset">
  </form>
 </body>
</html>

                                                                            http://www.java2all.com
Check.jsp :
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
 <title>Check.jsp</title>
 </head>
 <body>
  <%
  String name = request.getParameter("name");
  String password = request.getParameter("password");
  if(name.equals("Ashutosh") && password.equals("java"))
  { %>
  <jsp:forward page="Success.jsp"></jsp:forward>
  <% }
  else {
  %>
  <jsp:forward page="Retry.jsp"></jsp:forward>
  <%
  }
   %>
 </body>
</html>
                                                                            http://www.java2all.com
Retry.jsp :
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
 <title>Retry.jsp</title>
 </head>
 <body>
 Wrong User ID and Password, Please try again by click below link…………<br>
 <b><i><a href="Login.jsp"> Login page </a></i></b>
 </body>
</html>

Success.jsp :
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
 <title>Success.jsp</title>
 </head>
 <body>
 <h1>You are successfully login................. </h1>
 </body>
</html>
                                                                            http://www.java2all.com
Now run the Login.jsp in the appropriate
browser so you can get the below output,




                                         http://www.java2all.com
Now put the,
 User Name : aaaaaa
 Password : jjjjjj
    And click on Sign in button so you can get the
 below output in browser,
Output :
    Wrong User ID and Password, Please try again
 by click below link……………………..
 Login page
    By clicking the Login page link, the Login.jsp
 page is call and you can put the

                                          http://www.java2all.com
User Name : Ashutosh
Password : java
     And click on Sign in button so you can get the
  below output in browser,

Output :

     You are successfully login.................




                                                   http://www.java2all.com
(4)   <jsp:fallback>

  Syntax :

  <jsp:fallback> text message for user </jsp:fallback>

     A text message to display for the user if the
  plug-in cannot be started.
     If the plug-in starts but the applet or Bean does
  not, the plug-in usually displays a popup window
  explaining the error to the user.
     Its use with <jsp:plugin> element.       http://www.java2all.com
(5)   <jsp:plugin>

      By the use of <jsp:plugin> you can include an
  applet and JavaBean in your JSP page. Syntax of
  <jsp:plugin> is :




                                            http://www.java2all.com
Syntax :
<jsp:plugin type="bean|applet“
                  code="className.class“
                  codebase="Path of className.class
   after moving it in WebRoot“
  [ name="name of bean or applet instance" ]
  [ align="bottom|top|middle|left|right" ]
  [ height="displayPixels" ]
  [ width="displayPixels" ]
  [ jreversion=" version of Java Runtime
  environment " ]
    ................. >

                                              http://www.java2all.com
[<jsp:params>
  <jsp:param name="parameter_name"
         value="parameter_value" />
         ..........
         </jsp:params>]
       [<jsp:fallback>
         text messag..........
         </jsp:fallback>]
  </jsp:plugin>




                                      http://www.java2all.com
Example-1 :

       Write a simple application in which the applet is
    used in JSP file by <jsp:plugin> action element.

•      Create a Applet_Jsp.java file(applet) in default
    package at src in your Web Project(JSP_EXAMPLE).

       The source code of this java file(applet) are as
    under,


                                               http://www.java2all.com
Applet_Jsp.java :
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Applet_Jsp extends Applet implements ActionListener
{
  public void init()
    {
     setBackground(Color.black);
     Button r = new Button("RED");
     add(r);
     r.addActionListener(this);
     Button g = new Button("GREEN");
     add(g);
     g.addActionListener(this);
     Button b = new Button("BLUE");
     add(b);
     b.addActionListener(this);
  }
                                                                   http://www.java2all.com
public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals("RED"))
       setBackground(Color.red);
    if(e.getActionCommand().equals("BLUE"))
       setBackground(Color.blue);
    if(e.getActionCommand().equals("GREEN"))
       setBackground(Color.green);

    }
}

(2) Now, Run this applet.
(3) Create one new folder, name is AppletClass in
  WebRoot.
(3) Now,Copy the Applet_Jsp.class file(compile
   file/Bytecode file) which is available at……………
   workspace.metadata.me_tcatwebappsYour_Project_na
   meWEB-INFclasses Applet_Jsp.class in AppletClass folder
   in WebRoot.                                    http://www.java2all.com
(4) Create a Applet_Use_In_Jsp.jsp file in JSPFILES
  folder at your Web Project(JSP_EXAMPLE).
      The source code of this jsp file are as under,
Applet_Use_In_Jsp.jsp :
<%@ page language="java" %>
<html>
<head>
<title>Applet_Use_In_Jsp.jsp</title>
</head>
<body>
<jsp:plugin type="applet" code="Applet_Jsp.class" codebase="
     http://localhost:8080/JSP_EXAMPLE/AppletClass"
 width="500" height="500">
 <jsp:fallback>
  <p>Unable to load Applet..............</p>
  </jsp:fallback>
</jsp:plugin>
</body>
</html>                                                        http://www.java2all.com
•     <jsp:useBean>

       Forms are a very common method of
    interactions in web sites.The standard way of
    handling forms in JSP is to define a "bean".

       For that you just need to define a class that has
    a field corresponding to each field in the form.
    The class contains the "setters" and “getter”
    method of the form fields.
       By this action element <jsp:useBean>, we use
    java bean in a JSP page.
                                               http://www.java2all.com
Syntax :
     <jsp:useBean id="bean id" class="bean's class"
  scope="page|request|session| application" />

Scope of <jsp:useBean> :
1. page: This is default value. It means that we can
  use the Bean within the JSP page.
      It indicates that the bean is only available on the
  current page (stored in the PageContext of the
  current page).
2. request: It means that we can use the Bean from
  any JSP page processing the same request.
                                              http://www.java2all.com
A value of request indicates that the bean is only
  available for the current client request (stored in
  the ServletRequest object).
3. session:       It means that we use the Bean from
  any Jsp page in the same session as the JSP page
  that created the Bean.
      A value of session indicates that the object is
  available to all pages during the life of the current
  HttpSession.

4. application: It means that we use the Bean from
  any page in the same application as the Jsp page
  that created the Bean.                    http://www.java2all.com
A value of application indicates that it is
available to all pages that share the same
ServletContext.

(7)   <jsp:setProperty>

     This action sets the value of a bean’s property.
Syntax :

     <jsp:setProperty name="bean's id"
property="property Name”value="property value"/
>
                                               http://www.java2all.com
(8)   <jsp:getProperty>

     This element retrieves the value of a bean
property, converts it to a string, and inserts it into the
output.

Syntax :
     <jsp:getProperty name="bean's id"
     property="property name"/>

Example :        Write a simple program which
demonstrate the <jsp:useBean>,<jsp:getProperty>
and <jsp:setProperty> action elements.
                                                 http://www.java2all.com
Student_Data.java :
package bean;
public class Student_Data
{
   private String name = null;
   private String email = null;
   private int age = 0;

    public String getName()
       {
     return name;
   }
   public String getEmail()
      {
     return email;
   }
   public int getAge()
      {
     return age;
   }


                                  http://www.java2all.com
public void setName(String name)
       {
      this.name = name;
    }
    public void setEmail(String email)
       {
      this.email = email;
    }
    public void setAge(int age)
      {
      this.age = age;
    }
}




                                         http://www.java2all.com
BeanData.jsp :
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<html>
 <head>
 <title>BeanData.jsp</title>
 </head>
 <body>
  <jsp:useBean id="student" class="bean.Student_Data" scope="page">
    <jsp:setProperty name="student" property="name" value="Rahul"/>
    <jsp:setProperty name="student" property="email" value="rahul.kumar@gmail.com"/>
    <jsp:setProperty name="student" property="age" value="20"/>
  </jsp:useBean>
  <h1> <u> STUDENT DATA : </u> </h1>
  <p> Name : <i><jsp:getProperty name="student" property="name"/></i> </p>
  <p> Email-ID : <i><%= student.getEmail() %></i> </p>
  <p> Age : <i><jsp:getProperty name="student" property="age"/></i> </p>
 </body>
</html>




                                                                              http://www.java2all.com
Now run the BeanData.jsp in the appropriate
 browser so you can get the below output in the
 browser,

Output :
    STUDENT DATA :
    Name : Rahul
    Email-ID : rahul.kumar@gmail.com
    Age : 20



                                        http://www.java2all.com
http://www.java2all.com

Jsp element

  • 1.
    Chapter 2 JSP Element http://www.java2all.com
  • 2.
    JSP Element http://www.java2all.com
  • 3.
    In previous exampledescribed in introduction to JSP, We didn`t use any java statement or code in the file. If the developer wants to put any java code in that file then the developer can put it by the use of jsp tags(elements). There are mainly three group of jsp tags(elements) available in java server page : 1 ) JSP Scripting elements 2 ) JSP Directive elements 3 ) JSP Standard Action elements All three elements described in next three topic. http://www.java2all.com
  • 4.
    JSP Scripting elements http://www.java2all.com
  • 5.
    1. JSP Scriptingelements : There are four types of tag in jsp scripting elements. a) JSP Declaration tag. b) JSP scriptlet tag. c) JSP Expression tag. d) Comment tag. Now we describe each tag in detail. http://www.java2all.com
  • 6.
    a) JSP Declarationtag : A JSP declaration lets you declare or define variables and methods (fields) that use into the jsp page. Declaration tag Start with <%! And End with %> The Code placed inside this tag must end with a semicolon (;). Syntax: <%! Java Code; %> http://www.java2all.com
  • 7.
    <%! private inti = 10; %> <%! private int squre(int i) { i=i*i; return i; } %> You can also put these codes in a single syntax block of declaration like, <%! private int i = 10; private int squre(int i) { i=i*i; return i; } %> Note : The XML authors can use an alternative syntax for JSP declaration tag: http://www.java2all.com
  • 8.
    <jsp:declaration> Java code; </jsp:declaration> EX. <jsp:declaration> private int i = 1; </jsp:declaration> <jsp:declaration> { private int squre(int i) i=i*i; return i; } </jsp:declaration> You can also put these codes in a single syntax block of declaration like, <jsp:declaration> private int i = 1; private int squre(int i) { i=i*i; return i; } </jsp:declaration> http://www.java2all.com
  • 9.
    Remember that XMLelements, unlike HTML ones, are case sensitive. So be sure to use lowercase. Declarations do not generate any output so the developer uses declaration tag with JSP expression tag or JSP scriptlet tag for generating an appropriate output for display it in the appropriate browser. http://www.java2all.com
  • 10.
    b) JSP scriptlettag : A JSP scriptlet lets you declare or define any java code that use into the jsp page. scriptlet tag Start with <% and End with %> The Code placed inside this tag must end with a semicolon (;). Syntax: <% Java Code; %> http://www.java2all.com
  • 11.
    EX. <% int a = 10; out.print("a ="+a); %> Note : The XML authors can use an alternative syntax for JSP scriptlet tag. <jsp:scriptlet> Java code; </jsp:scriptlet> http://www.java2all.com
  • 12.
    c) JSP Expressiontag : A JSP expression is used to insert Java values directly into the output. JSP Expression tag is use for evaluating any expression and directly displays the output in appropriate web browser. Expression tag Start with <%= and End with %> The Code placed inside this tag not end with a semicolon (;). Syntax: <%= Java Code %> http://www.java2all.com
  • 13.
    For example. thefollowing shows the date/time that the page was requested: Current time: <%= new java.util.Date() %> Note : The XML authors can use an alternative syntax for JSP expressions: <jsp:expression> Java Expression </jsp:expression> http://www.java2all.com
  • 14.
    d) Comment tag: Although you can always include HTML comments in JSP pages, users can view these if they view the page's source. If you don't want users to be able to see your comments, embed them within the < %-- ... --%> tag. <html> <head> <title>Comment demo</title> </head> <body> <p>This is simple demo of test the comment </p> <!-- This is a comment. Comments are not displayed in the browser but displayed in view source --> <%-- This is a comment. Comments are not displayed in the browser as well as not displayed in view source also --%> </body> </html> http://www.java2all.com
  • 15.
    Output : This is simple demo of test the comment. Now right click on the browser and select the view source so we can get the code in Notepad like, <html> <head> <title>Comment demo page</title> </head> <body> <p>This is simple demo of test the comment. </p> <!-- This is a comment. Comments are not displayed in the browser but displayed in view source --> </body> </html> In the view sorce code, the comment put in <%-- comment --%> will not display but the comment put in <!—comment will display. http://www.java2all.com
  • 16.
    Now using theseJSP Scripting elements, we are developing some simple examples so the use of these tags can easily understood. <html> <head> <title>Scripting Demo page</title> </head> <body> <%-- declaration tag --%> <%! int i = 10; %> <%-- scriptlet tag --%> <% out.print("i = "+i); %> <br> <br> <% out.print("for loop execution start..........."); %> <br> <% for(int j=1;j<=10;j++) { out.print("j = "+j); %> <br> <% } http://www.java2all.com
  • 17.
    out.print("for loop executioncomplete..........."); %> <br> <br> <%-- expression tag --%> <%! int a = 10; int b = 20; %> The addition of two variable : a + b = 10 + 20 = <%= a+b %> <br> <br> Current time : <%= new java.util.Date() %> </body> </html http://www.java2all.com
  • 18.
    Output : i= 10 for loop execution start........... j=1 j=2 j=3 j=4 j=5 j=6 j=7 j=8 j=9 j = 10 for loop execution complete........... The addition of two variable : a + b = 10 + 20 = 30 Current time : Sun Feb 12 14:00:35 IST 2012 http://www.java2all.com
  • 19.
    JSP Directive elements http://www.java2all.com
  • 20.
    2. JSP Directiveelements : A JSP directive gives special information about the page to JSP Engine. Each JSP goes through two phases: (1) The first phase is known as translation time, during which the JSP engine turns the file into a servlet. (The step following from 1 to 5 in JSP Architecture) http://www.java2all.com
  • 21.
    The second phase is known as request time, during which the resulting servlet is run to actually generate the page. (The step following from 6 to 9 in JSP Architecture) The JSP engine handles the directives at translation time because the JSP engine will translate a particular directive into a servlet only for the first time so the developer can get more speed for the process of loading a JSP file in a future. Syntax: <%@ directive-name [attribute=”value” attribute=”value”………….] %> http://www.java2all.com
  • 22.
    Note : TheXML syntax for defining directives is <jsp:directive.directiveType [attribute=”value” attribute=”value”………….] /> Three main types of directives are: a) page directive b) include directive c) taglib directive http://www.java2all.com
  • 23.
    a) page directive: The page directive is used to specify attributes for the JSP page as a whole. The page directive does not produce any visible output when the page is requested but change the way the JSP Engine processes the page. e.g., you can make session data unavailable to a page by setting a session to FALSE. http://www.java2all.com
  • 24.
    Syntax: <@ page [attribute=”value” attribute=”value”………….] %> The table given below describes the possible attributes for the page directive. http://www.java2all.com
  • 25.
    Syntax Attribute Description (default value is Example in bold) This tells the server about the language to be used <%@ page language in the JSP file. Presently language="java" language="java" the only valid value for %> this attribute is java. This attribute defines the import="packag <%@ page Import list of packages, each e.class" import="java.util. separated by comma . *, java.io.*"%> Indicates the superclass <%@ page extends="packa Extends of servlet when jsp extends="com.Co ge.class" translated in servlet. nnect"%> http://www.java2all.com
  • 26.
    true indicates session should be bound to the existing session if one exists, otherwise a new session="true| <%@ page Session session should be created false" session="true"%> and bound to it and false indicates that no sessions will be used. specifies the buffer size buffer="sizekb| <%@ page Buffer for out and default is 8kb. none" buffer="8kb"%> True indicates multithreading and false <%@ page isThreadSafe="tr isThreadSafe indicates that the servlet isThreadSafe="tr ue|false" should implement ue"%> SingleThreadModel http://www.java2all.com
  • 27.
    true indicates thatthe buffer should be flushed when it is full and false autoflush="tru <%@ page autoFlush indicates indicates that e|false" autoFlush="true"%> an exception should be thrown when the buffer overflows. <%@ page This defines a string that info="This is a simple info="message Info can be retrieved via the jsp file created by " getServletInfo method. Java2all team on 22 Feb 2011"%> <%@ page pageEncodin This defines data type of pageEncoding= pageEncoding="ISO- g page encoding. "ISO-8859-1" 8859-1"%> contentType This specifies the MIME contentType=" <%@ page type of the output. MIME-Type" contentType="text/h tml; charset=ISO-8859-1" http://www.java2all.com
  • 28.
    <%@ page This defines isELIgnored=" isELIgnored isELIgnored="false ENUM data type. true|false " "%> This indicates whether or not <%@ page isErrorPage="true isErrorPage the current page isErrorPage="false |false" can act as the "%> error page. Define a URL to another JSP that is invoked if an <%@ page errorPage unchecked errorPage="url" errorPage="error.j runtime sp"%> exception is thrown. http://www.java2all.com
  • 29.
    <%@ page language="java" import="java.util.*,java.io.*" extends="com.Connect" autoFlush="true" errorPage="error.jsp" info="This is a simple jsp file created by Java2all team on 22 Feb 2011" isELIgnored="false" isErrorPage="false" session="true" buffer="8kb" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isThreadSafe="true" %> NOTE : The XML equivalent of <%@ page import="java.util.*" %> is <jsp:directive.page import="java.util.*" /> http://www.java2all.com
  • 30.
    b) include directive: It allows a JSP developer to include source code (static resource) of a file inside jsp file at the specified place at a translation time. Typically include files are used for headers, footers, tables and navigation that are common to multiple pages. The included page should not be another dynamic page so the included file does not need to be a complete and valid JSP or servlet. http://www.java2all.com
  • 31.
    Syntax: <%@ include file="/folder_name/file_name"%> If the included file and JSP file are available in the same folder then the folder name is not required in syntax. <%@ include file="file_name"%> Now we are describe the include directive by one simple example so the use of include directive in JSP file is easily understand. http://www.java2all.com
  • 32.
    Step-1 : Create two folder in webRoot (i) HTMLFILE and (ii) JSPFILE. Step-2 : Create a new HTML file(Included.html) in HTMLFILE folder. Step-3 : Replace the source code of a file(Included.html) by the below code. <html> <head> <title> Included.html </title> </head> <body> <b>This is HTML page which is include in JSP file by using directive include tag in JSP file.</b> <br> </body> </html> http://www.java2all.com
  • 33.
    Step-4 : Create a jsp file(IncludeDemo.jsp) in JSPFILE folder. Step-5 : Now replace the source code of a file(IncludeDemo.jsp) by the below code. <%@ page language="java" import="java.util.*,java.io.*" pageEncoding="ISO-8859-1"%> <html> <head> <title> IncludeDemo.jsp </title> </head> <body> This is a JSP page. <br> <%@ include file="/HTMLFILE/“Included.html"%> </body> </html> http://www.java2all.com
  • 34.
    Step-6 : Now Redeploy the Project and start the Server. Step-7 : Enter the appropriate URL in web- browser. http://www.java2all.com
  • 35.
    Output : This is a JSP page. This is HTML page which is include in jsp file by using directive include tag in jsp file. http://www.java2all.com
  • 36.
    c) taglib directive: The taglib directive makes custom actions available in current page through the use of tag library. Syntax: <%@ taglib uri="tag Library_path" prefix="tag_prefix"%> uri ====> The absolute path (URL) of a Tag Library Descriptor. prefix ====> A unique prefix used to identify custom tags from library used later in the JSP page. http://www.java2all.com
  • 37.
    EX. <%@ taglib uri="/tlds/TableGenerator.tld" prefix="tg"%> And if TableGenerator.tld defines a tag named table, then the JSP file can contain tag of following type: <tg:table> ………. ………. </tg:table> NOTE : We discuss taglib directory in detail in further chapter. http://www.java2all.com
  • 38.
    JSP Standard Actionelements http://www.java2all.com
  • 39.
    JSP Standard Actionelements: Actions are high-level JSP elements that create, modify or use other objects. Unlike directives and scripting elements, JSP are coded using strict XML syntax form. By the use of JSP actions elements you can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin etc. http://www.java2all.com
  • 40.
    The standard actiontypes are: (1) <jsp:param> (2) <jsp:include> (3) <jsp:forward> (4) <jsp:fallback> (5) <jsp:plugin> (6) <jsp:useBean> (7) <jsp:setProperty> (8) <jsp:getProperty> http://www.java2all.com
  • 41.
    (1) <jsp:param> The <jsp:param> action is used to provide other tags with additional information in the form of name value pairs. This action is used in conjunction with jsp:include, jsp:forward and jsp:plugin actions. Syntax : <jsp:param name=”parameter_name” value=”parameter_value” /> http://www.java2all.com
  • 42.
    OR <jsp:param name=”parameter_name” value=”parameter_value”> </ jsp:param> For Example, <jsp:param name=”font_size” value=”20” /> OR <jsp:param name=”font_size” value=”20”> </jsp:param > http://www.java2all.com
  • 43.
    (2) <jsp:include> This action allows a static or dynamic resource to be including in the JSP at request time. If page is buffered then the buffer is flushed prior to the inclusion. Syntax : <jsp:include page= “file_name” flush = “true|false” /> http://www.java2all.com
  • 44.
    OR <jsp:include page= “file_name”flush = “true|false” > <jsp:param name=”parameter_name” value=”parameter_value” /> </jsp:include > NOTE : A <jsp:include> action may have one or more <jsp:param> tags in its body, to provide additional name-value pairs. http://www.java2all.com
  • 45.
    Included.jsp :- <%@ pagelanguage="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Included.jsp</title> </head> <body> This is the message of Included.jsp file..............<br> </body> </html> Include.jsp :- <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Include.jsp</title> </head> <body> This is the message of Include.jsp file..............<br> <jsp:include page="Included.jsp" /> </body> </html> http://www.java2all.com
  • 46.
    Now run theIncluded.jsp in the appropriate browser so you can get the below output in the browser, Output: This is the message of Include.jsp file.............. This is the message of Included.jsp file.............. Example-2 : Write a simple program which demonstrate the use of <jsp:param> in <jsp:include> action element. http://www.java2all.com
  • 47.
    Employee.jsp :- <%@ pagelanguage="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Employee.jsp</title> </head> <body> <b><i><% out.print("Name : "+request.getParameter("name1")); %></i></b> <br> <% out.print("He is a "+request.getParameter("profile1")+" dept. in Noble Engineering College - Junagadh."); %> <br> <b><i><% out.print("Name : "+request.getParameter("name2"));%></i></b><br> <% out.print("He is a "+request.getParameter("profile2")+" dept. in Noble Engineering College - Junagadh."); %> </body> </html> http://www.java2all.com
  • 48.
    Information.jsp :- <%@ pagelanguage="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Information.jsp</title> </head> <body> <jsp:include page="Employee.jsp"> <jsp:param value="Prof. Ashutosh A. Abhangi" name="name1"/> <jsp:param value="H.O.D. of Info. Tech. " name="profile1"/> <jsp:param value="Prof. Kamal N. Kotecha" name="name2"/> <jsp:param value="H.O.D. of C.S.E. " name="profile2"/> </jsp:include> </body> </html> http://www.java2all.com
  • 49.
    Now run theInformation.jsp in the appropriate browser so you can get the below output in the browser, Output: Name : Prof. Ashutosh A. Abhangi He is a H.O.D. of Info. Tech. dept. in Noble Engineering College - Junagadh. Name : Prof. Kamal N. Kotecha He is a H.O.D. of C.S.E. dept. in Noble Engineering College - Junagadh. http://www.java2all.com
  • 50.
    NOTE : Differencebetween Directive include and Action include element. Included Include Syntax Done when Parsing Content <%@include file=”file_na Compilation Directive Static Container me”%> time <jsp:include Request Not parsed Static or Action page=”file_n Processing but included dynamic ame”%> time in container http://www.java2all.com
  • 51.
    (3) <jsp:forward> With the forward action, the current page stops processing the request and forwards the request to another page. Execution never returns to the calling (current) page. Syntax : <jsp:forward page= “file_name” /> OR <jsp: forward page= “file_name”> <jsp:param name=”parameter_name” value=”parameter_value” /> </jsp: forward> http://www.java2all.com
  • 52.
    The meaning aswell as use of the attributes and the <jsp:param> element are same as for <jsp:Include> action element. Example-1 : Write a simple program which demonstrate the <jsp:forward> action element. Current.jsp : <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Current.jsp</title> </head> <body> This is a Current page <jsp:forward page="Forward.jsp" /> </body> </html> http://www.java2all.com
  • 53.
    Forward.jsp : <%@ pagelanguage="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Forward.jsp</title> </head> <body> Welcome, Forward is working now and this is a Forwarded page...............<br/> </body> </html> Now run the Current.jsp in the appropriate browser so you can get the below output in the browser, Output: Welcome, Forward is working now and this is a Forwarded page............... http://www.java2all.com
  • 54.
    Example-2 : Write a simple Login Application by using <jsp:forward> action element. Login.jsp : <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Login.jsp</title> </head> <body> <form action="Check.jsp"> User Name : <input type="text" name="name"> <br> Password : <input type="text" name="password"> <br> <input type="submit" value="Sign in"> <input type="reset" value="Reset"> </form> </body> </html> http://www.java2all.com
  • 55.
    Check.jsp : <%@ pagelanguage="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Check.jsp</title> </head> <body> <% String name = request.getParameter("name"); String password = request.getParameter("password"); if(name.equals("Ashutosh") && password.equals("java")) { %> <jsp:forward page="Success.jsp"></jsp:forward> <% } else { %> <jsp:forward page="Retry.jsp"></jsp:forward> <% } %> </body> </html> http://www.java2all.com
  • 56.
    Retry.jsp : <%@ pagelanguage="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Retry.jsp</title> </head> <body> Wrong User ID and Password, Please try again by click below link…………<br> <b><i><a href="Login.jsp"> Login page </a></i></b> </body> </html> Success.jsp : <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>Success.jsp</title> </head> <body> <h1>You are successfully login................. </h1> </body> </html> http://www.java2all.com
  • 57.
    Now run theLogin.jsp in the appropriate browser so you can get the below output, http://www.java2all.com
  • 58.
    Now put the, User Name : aaaaaa Password : jjjjjj And click on Sign in button so you can get the below output in browser, Output : Wrong User ID and Password, Please try again by click below link…………………….. Login page By clicking the Login page link, the Login.jsp page is call and you can put the http://www.java2all.com
  • 59.
    User Name :Ashutosh Password : java And click on Sign in button so you can get the below output in browser, Output : You are successfully login................. http://www.java2all.com
  • 60.
    (4) <jsp:fallback> Syntax : <jsp:fallback> text message for user </jsp:fallback> A text message to display for the user if the plug-in cannot be started. If the plug-in starts but the applet or Bean does not, the plug-in usually displays a popup window explaining the error to the user. Its use with <jsp:plugin> element. http://www.java2all.com
  • 61.
    (5) <jsp:plugin> By the use of <jsp:plugin> you can include an applet and JavaBean in your JSP page. Syntax of <jsp:plugin> is : http://www.java2all.com
  • 62.
    Syntax : <jsp:plugin type="bean|applet“ code="className.class“ codebase="Path of className.class after moving it in WebRoot“ [ name="name of bean or applet instance" ] [ align="bottom|top|middle|left|right" ] [ height="displayPixels" ] [ width="displayPixels" ] [ jreversion=" version of Java Runtime environment " ] ................. > http://www.java2all.com
  • 63.
    [<jsp:params> <jsp:paramname="parameter_name" value="parameter_value" /> .......... </jsp:params>] [<jsp:fallback> text messag.......... </jsp:fallback>] </jsp:plugin> http://www.java2all.com
  • 64.
    Example-1 : Write a simple application in which the applet is used in JSP file by <jsp:plugin> action element. • Create a Applet_Jsp.java file(applet) in default package at src in your Web Project(JSP_EXAMPLE). The source code of this java file(applet) are as under, http://www.java2all.com
  • 65.
    Applet_Jsp.java : import java.applet.Applet; importjava.awt.Button; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Applet_Jsp extends Applet implements ActionListener { public void init() { setBackground(Color.black); Button r = new Button("RED"); add(r); r.addActionListener(this); Button g = new Button("GREEN"); add(g); g.addActionListener(this); Button b = new Button("BLUE"); add(b); b.addActionListener(this); } http://www.java2all.com
  • 66.
    public void actionPerformed(ActionEvente) { if(e.getActionCommand().equals("RED")) setBackground(Color.red); if(e.getActionCommand().equals("BLUE")) setBackground(Color.blue); if(e.getActionCommand().equals("GREEN")) setBackground(Color.green); } } (2) Now, Run this applet. (3) Create one new folder, name is AppletClass in WebRoot. (3) Now,Copy the Applet_Jsp.class file(compile file/Bytecode file) which is available at…………… workspace.metadata.me_tcatwebappsYour_Project_na meWEB-INFclasses Applet_Jsp.class in AppletClass folder in WebRoot. http://www.java2all.com
  • 67.
    (4) Create aApplet_Use_In_Jsp.jsp file in JSPFILES folder at your Web Project(JSP_EXAMPLE). The source code of this jsp file are as under, Applet_Use_In_Jsp.jsp : <%@ page language="java" %> <html> <head> <title>Applet_Use_In_Jsp.jsp</title> </head> <body> <jsp:plugin type="applet" code="Applet_Jsp.class" codebase=" http://localhost:8080/JSP_EXAMPLE/AppletClass" width="500" height="500"> <jsp:fallback> <p>Unable to load Applet..............</p> </jsp:fallback> </jsp:plugin> </body> </html> http://www.java2all.com
  • 68.
    <jsp:useBean> Forms are a very common method of interactions in web sites.The standard way of handling forms in JSP is to define a "bean". For that you just need to define a class that has a field corresponding to each field in the form. The class contains the "setters" and “getter” method of the form fields. By this action element <jsp:useBean>, we use java bean in a JSP page. http://www.java2all.com
  • 69.
    Syntax : <jsp:useBean id="bean id" class="bean's class" scope="page|request|session| application" /> Scope of <jsp:useBean> : 1. page: This is default value. It means that we can use the Bean within the JSP page. It indicates that the bean is only available on the current page (stored in the PageContext of the current page). 2. request: It means that we can use the Bean from any JSP page processing the same request. http://www.java2all.com
  • 70.
    A value ofrequest indicates that the bean is only available for the current client request (stored in the ServletRequest object). 3. session: It means that we use the Bean from any Jsp page in the same session as the JSP page that created the Bean. A value of session indicates that the object is available to all pages during the life of the current HttpSession. 4. application: It means that we use the Bean from any page in the same application as the Jsp page that created the Bean. http://www.java2all.com
  • 71.
    A value ofapplication indicates that it is available to all pages that share the same ServletContext. (7) <jsp:setProperty> This action sets the value of a bean’s property. Syntax : <jsp:setProperty name="bean's id" property="property Name”value="property value"/ > http://www.java2all.com
  • 72.
    (8) <jsp:getProperty> This element retrieves the value of a bean property, converts it to a string, and inserts it into the output. Syntax : <jsp:getProperty name="bean's id" property="property name"/> Example : Write a simple program which demonstrate the <jsp:useBean>,<jsp:getProperty> and <jsp:setProperty> action elements. http://www.java2all.com
  • 73.
    Student_Data.java : package bean; publicclass Student_Data { private String name = null; private String email = null; private int age = 0; public String getName() { return name; } public String getEmail() { return email; } public int getAge() { return age; } http://www.java2all.com
  • 74.
    public void setName(Stringname) { this.name = name; } public void setEmail(String email) { this.email = email; } public void setAge(int age) { this.age = age; } } http://www.java2all.com
  • 75.
    BeanData.jsp : <%@ pagelanguage="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <html> <head> <title>BeanData.jsp</title> </head> <body> <jsp:useBean id="student" class="bean.Student_Data" scope="page"> <jsp:setProperty name="student" property="name" value="Rahul"/> <jsp:setProperty name="student" property="email" value="rahul.kumar@gmail.com"/> <jsp:setProperty name="student" property="age" value="20"/> </jsp:useBean> <h1> <u> STUDENT DATA : </u> </h1> <p> Name : <i><jsp:getProperty name="student" property="name"/></i> </p> <p> Email-ID : <i><%= student.getEmail() %></i> </p> <p> Age : <i><jsp:getProperty name="student" property="age"/></i> </p> </body> </html> http://www.java2all.com
  • 76.
    Now run theBeanData.jsp in the appropriate browser so you can get the below output in the browser, Output : STUDENT DATA : Name : Rahul Email-ID : rahul.kumar@gmail.com Age : 20 http://www.java2all.com
  • 77.

Editor's Notes

  • #16 White Space Characters
  • #17 White Space Characters
  • #22 White Space Characters
  • #26 White Space Characters
  • #27 White Space Characters
  • #31 White Space Characters
  • #38 White Space Characters
  • #40 White Space Characters