SlideShare a Scribd company logo
1 of 110
Download to read offline
CS3002
Lecture 1 / Slide 1




                            CS3002
                      Software Technologies
                           Lecture 12
CS3002
Lecture 1 / Slide 2




   Responsibilities of Servlets
        Coding the presentation logic and business logic
        together is not a good practice
             A change in any one of these requires the modification of the
             entire code
             Programmers with different skill sets are required for
             creating and maintaining these
        Servlets, being Java programs, are best suited for
        coding business logic
CS3002
Lecture 1 / Slide 3




   Responsibilities of Servlets
        Servlets are not suitable to code presentation logic
             It is not easy to mix static contents with dynamic contents in
             Servlets
             As Servlets are not as easy as HTML, it will be difficult for
             web designers to use this technology
        A technology with the power of Servlets and ease of
        HTML is required to code presentation logic, so that
        web designers can also easily use it
CS3002
Lecture 1 / Slide 4




   JSP
        JSP or JavaServer Pages is a technology developed by
        Sun Microsystems for coding the presentation layer of
        an enterprise application
        A JSP file is very similar to an HTML file
        Unlike HTML files, JSP files will contain some Java
        code also with in <% %> tags
        Ex: LongMessageJSP
CS3002
Lecture 1 / Slide 5




   JSP
        When a client requests for a JSP, the Server (For
        example, Tomcat), sends the HTML tags as such to the
        browser
        The code between <% and %> will be compiled,
        executed and the output will be send to the browser
        JSP
             Can be used to code presentation logic
             Can be used to generate dynamic pages
             Is as simple as HTML, even web designers can use it easily
CS3002
Lecture 1 / Slide 6




   Servlets Vs JSP
        Servlet
             Bits of HTML embedded in Java code
             Suitable for coding the business layer of an enterprise
             application
             Created and maintained by Java programmers
        JSP
             Bits of Java code embedded in HTML
             Suitable for coding the presentation layer of an enterprise
             application
             Created and maintained by web designers
CS3002
Lecture 1 / Slide 7

   JSP
        Internally, the JSP is getting converted to a Servlet
        When a user requests for a .jsp file for the first time, the
        JSP Container will create a Servlet that would produce
        the output that the .jsp file is supposed to produce
        The Servlet is compiled, run and the output is given to
        the browser
        Starting from the second request, there is no overhead
        of compilation
                                             IS
          CLIEN         Request JSP        VALID     No
            T                                 ?
                                 Text                  COMPILE
                      Response SERVLET         Yes

                               Class
CS3002
Lecture 1 / Slide 8




   JSP
    Ex: LongMessageJSP_jsp.java
    In Netbeans its found under,
   Webapplication folder -> build -> generated -> src -> org
    -> apache -> jsp -> LongMessageJSP_jsp.java
CS3002
Lecture 1 / Slide 9

   Implicit Objects some implicit objects
     A JSP developer can use
        Some of the important objects and their classes are as follows
           out -        JSPWriter
           request - HttpServletRequest
           response- HttpServletResponse
           session - HttpSession
           application - ServletContext
           config - ServletConfig
           exception - Throwable / JspException
           pageContext- PageContext
           page     - Object
        These objects will be declared by the generated Servlet and
        hence the statements we write in JSP using these variables will
        get a meaning once they are pasted in the Servlet code
CS3002
Lecture 1 / Slide 10



       Directives         //no output to client
            page
            include
            taglib
       Scripting elements
            Scriptlet
            Declaration
            expression
       Standard actions
            forward
            include
            useBean
CS3002
Lecture 1 / Slide 11


   Implicit Objects - Example
       This example uses the out, request and session objects
       Ex: SessionTestJSPForm.html
       SessionTestJSP
       ReadSessionTestJSP
CS3002
Lecture 1 / Slide 12




   JSP tags
                       SCRIPTING TAGS
                       DIRECTIVE TAGS
                        ACTION TAGS
                       CUSTOM TAGS
CS3002
Lecture 1 / Slide 13




   Tags in JSP
       Tags in JSP can be categorized as
            Comments
            Scripting elements
            Directive elements
            Action elements
            Template data
             – Any thing other than the above mentioned four categories
               fall under template data
             – This will include all HTML tags and text
CS3002
Lecture 1 / Slide 14



   Comments
       Just like any other HTML tag, standard HTML
       comment tag also can be used in JSP
                   <!--
                   <!-- This is a comment in HTML -->
                                                  -->


             This comment tag will reach the browser
             A JSP specific comment tag is written as follows
                   <%--
                   <%-- This is a JSP Comment --%>
                                              --%>


            This comment tag will not reach the browser
CS3002
Lecture 1 / Slide 15




   Character quoting conventions
   To get “<%” character in text (static HTML)   <%
   To get “%>” character in scripting elements   %>
   To get a single quote in an attribute         '
   To get a double quote in an attribute         "
CS3002
Lecture 1 / Slide 16




   Scripting tags
   SCRIPTING TAGS are three types

                        SCRIPTLET TAGS

                       EXPRESSION TAGS

                       DECLARATION TAGS
CS3002
Lecture 1 / Slide 17




   Scripting Elements
       Scripting elements are elements in the page that include
       the Java code
       JSP can contain 3 types of scripting elements
            Scriptlets     <%    %>
            Declarations   <%!   %>
            Expressions    <%=   %>
CS3002
Lecture 1 / Slide 18


   Scripting Elements - Scriptlets
        The Java statements that appear between <% and %>
        are called scriptlets
        This code goes to _jspService() method of servlet
        Java statements end in semicolon
        Ex: TestJSP
CS3002
Lecture 1 / Slide 19
    Scripting Elements - Declaration of variables
       Variables declared within <% and %> will be local to
       the service method of the generated Servlet and each
       request will have a separate copy of this variable
                 <%
                       int data;
                 %>

         Declarative tag
         Variables declared within <%! and %> will be a data
         member of the generated Servlet class and all the requests
         will use the same copy of this variable
                  <%!
                       double amount;
                  %>
CS3002
Lecture 1 / Slide 20


   Scripting Elements - Declaration of methods

       Methods also can be declared using scripting elements
       All variables and methods should be declared within
       <%! and %> and they become a method of the
       generated Servlet
       Ex: MethodTestJSPForm.html
       MethodTestJSP
CS3002
Lecture 1 / Slide 21




   Declaration tag
   <html><body>
   <%!
       int addNum(int n, int m) {
               return n + m;
   }
       int subtractNum(int N1, int N2) {
               return N1 - N2;
   }
   %>
   <% out.println("6 + 2 = " + addNum(6, 2)); %>
   <% out.println("8 - 5 = " + subtractNum(8, 5) + "<BR>");
   </body></html>
CS3002
Lecture 1 / Slide 22


   Handling form in jsp
<html> <head><title>Using Post Method in JSP Form.</title></head> <body> <form
   method="post"> <table border="0" cellpadding="0" cellspacing="0"> <tr>
   <td>Enter your name: </td>
           <td><input type="text" size="20" name="txtName" /></td> </tr>
<tr> <td>&nbsp;</td> <td><input type="submit" name="B1" value="Submit" />
<input type="reset" name="B2" value= "Reset" /></td> </tr>
</table> </form>
<% if(request.getParameter("txtName") != null)
    {
            if(request.getParameter("txtName"). equals(""))
           out.println("<html><font color=red>Please enter your name.</font></html>");
           else
           out.println("Your username is: " + request.getParameter("txtName"));
} %>
</body> </html>
CS3002
Lecture 1 / Slide 23


   Validating using javascript in jsp
  ….
  <% if(ent==0)
  String insertQry = "insert Employee values('"+code+"','"+empname+"')";
     int val = stmt.executeUpdate(insertQry);
     %>
     <script language="javascript">
     alert("Insertion successful");
     document.location="EmplyeeInformation.jsp";
     </script>
     <% } if(ent==1) { %>
     <script language="javascript">
     alert("This Emp ID already Exists");
     document.location="EmplyeeInformation.jsp";
     </script> <% } stmt.close(); con.close(); }
     catch(Exception e) {
     out.println(e.toString());
     }
     %>
CS3002
Lecture 1 / Slide 24




   Initialization parameters
   <servlet>
      <servlet-name>MyTestInit</servlet-name>
      <jsp-file>/TestInit.jsp</jsp-file>
      <init-param>
         <param-value>name</param-name>
         <param-value>abc</param-value>
      </init-param>
   </servlet>
   web.xml
CS3002
Lecture 1 / Slide 25

   Scripting Elements - Declaration of JSP Lifecycle methods
       The code that should be executed only once when the
       JSP is invoked for the first time can be coded in a
       method jspInit()
       The jspInit() method will be executed only once per JSP,
       not per request
       Typically this method contains code for initialization
       The code that should be executed only once when the
       JSP is unloaded from the memory can be coded in a
       method jspDestroy()
       Typically this method contains code to cleanup the
       resources used by the JSP
CS3002
Lecture 1 / Slide 26




   JSP Lifecycle
    javax.servlet.jsp.JspPage
   methods jspInit(), jspDestroy()

       javax.servlet.jsp.HttpJspPage extends
      javax.servlet.jsp.JspPage
   methods
      _ jspService(HttpServletRequest,HttpServletResponse)
   // can’t override this!!!
   Ex: LifecycleTestJSPForm.html, LifecycleTestJSP
CS3002
Lecture 1 / Slide 27



    Scripting Elements - Expressions
       The value of an expression can be printed to the
       browser using the syntax <%=expression%>
            <%
                  String name = “Software”;
            %>
            Hello <%=name%>


       These expressions doesn’t end with semi-colon. These
       are passed as argument to out.print()
CS3002
Lecture 1 / Slide 28


   Access all the fields from table through JSP
   <%
     String QueryString = "SELECT * from stu_info";
     rs = statement.executeQuery(QueryString);
     %>
     <TABLE cellpadding="15" border="1" style="background-
     color: #ffffcc;"> <% while (rs.next()) { %> <TR>
     <TD> <%=rs.getInt(1)%> </TD>
     <TD><%=rs.getString(2)%> </TD>
     <TD> <%=rs.getString(3)%> </TD>
     <TD> <%=rs.getString(4)%> </TD> </TR>
     <% } %>
CS3002
Lecture 1 / Slide 29

  Servlet and JSP
         String sql = "select * from message";
           Statement s = connection.createStatement();
           s.executeQuery (sql);
           rs = s.getResultSet();
           while (rs.next ()){
             //Add records into data list
             dataList.add(rs.getInt("id"));
             dataList.add(rs.getString("message")); }…..
               request.setAttribute("data",dataList);
       RequestDispatcher dispatcher = request.getRequestDispatcher(DataPage.jsp);
       if (dispatcher != null){ dispatcher.forward(request, response); }
   DataPage.Jsp
   <body> <table border="1" width="303">
      <tr><td width="119"><b>ID</b></td><td width="168"><b>Message</b></td></tr>
      <%Iterator itr;%>
      <% List data= (List)request.getAttribute("data");
            for (itr=data.iterator(); itr.hasNext(); ) {
            %>
   <tr><td width="119"><%=itr.next()%></td><td width="168"><%=itr.next()%></td></tr>
            <%}%> </table></body>
CS3002
Lecture 1 / Slide 30


  Authentication
   <%@ page import="java.sql.*" %>
   <% String sql = "select user,password from User";
         Statement s = connection.createStatement();
         s.executeQuery (sql);
         rs = s.getResultSet();
         while (rs.next ()){
          userName=rs.getString("user");
          passwrd=rs.getString("password");
         } %>
   <%
   if(userName.equals(request.getParameter("user")) &&
              passwrd.equals(request.getParameter("pass"))){
            out.println("User Authenticated");
          }
          else{
            out.println("You are not an authentic person");
          } %>
CS3002
Lecture 1 / Slide 31

   image
<%
psmnt = connection.prepareStatement("SELECT image FROM save_image WHERE id
   = ?");
   psmnt.setString(1, "11"); // here integer number '11' is image id from the table
   rs = psmnt.executeQuery();
   if(rs.next()) {
          byte[] bytearray = new byte[1048576];
          int size=0;
          sImage = rs.getBinaryStream(1);
          response.reset();
          response.setContentType("image/jpeg");
          while((size=sImage.read(bytearray))!= -1 ){
               response.getOutputStream().write(bytearray,0,size);
          } } %>
save_image table
    CREATE TABLE save_image ( id int(5) NOT NULL auto_increment, name
    varchar(25) default NULL, city varchar(20) default NULL, image blob, Phone
    varchar(15) default NULL, PRIMARY KEY (`id`) );
CS3002
Lecture 1 / Slide 32


   Retrieving data from a file
   <%@ page import="java.io.*"%>
     <html><body>
     <%
        String fName = "c:csvmyfile.csv";
        String thisLine; int count=0; int i=0;
        FileInputStream fis = new FileInputStream(fName);
        DataInputStream myInput = new DataInputStream(fis); %>
     <table>
     <% while ((thisLine = myInput.readLine()) != null)
           {
                String strar[] = thisLine.split(",");
                for(int j=0;j<strar.length;j++) {
                     if(i!=0) {
                          out.print(" " +strar[j]+ " ");
                     } else { out.print(" <b>" +strar[j]+ "</b> "); }
                } out.println("<br>"); i++;
           } %> </table> </body> </html>
CS3002
Lecture 1 / Slide 33




   Export data to a file from database
   http://www.roseindia.net/jsp/jdbccsv.shtml

   Downloading a file from database
   http://www.roseindia.net/jsp/downloadcsv.shtml
CS3002
Lecture 1 / Slide 34




   Reading request information
       <%= request.getMethod() %>
       <%= request.getRequestURI() %>
       <%= request.getProtocol() %>
       <%= request.getQueryString() %>
       <%= request.getContentType() %>
       <%= request.getServerName() %>
       <%= request.getRemoteUser() %>
       …
CS3002
Lecture 1 / Slide 35


   Retrieving data posted to a jsp file
   from html file
       <input type=“text” name=“username” size=“20”>



   <html><body>
   <%=request.getParameter(“username”) %>
   </body></html>
CS3002
Lecture 1 / Slide 36




   Directive tags
   DIRECTIVE TAGS are three types

                        PAGE DIRECTIVE

                       INCLUDE DIRECTIVE

                       TAGLIB DIRECTIVE
CS3002
Lecture 1 / Slide 37


   Directive Elements
       Directive elements provide information to the JSP
       container about the page
       JSP can contain three types of directives
         page
         include
         taglib
       Syntax
       <%@ directive attribute="value" %>
       <%@ directive attribute1="value1“ attribute2="value2“
       ...attributeN="valueN" %>
CS3002
Lecture 1 / Slide 38


   The page Directive
       The page directive has the following form
          <%@ page attributes %>
        Some of the important attributes are
          import
          session
          contentType
          errorPage
          isErrorPage
          isThreadSafe, isELIgnored, language, extends,
          session, buffer, autoFlush, info, pageEncoding
CS3002
Lecture 1 / Slide 39




   The page Directive - import
         The import attribute
          – Example

<%@ page import = “java.io.*,java.net.Socket” %>

     – Just like a normal Java program, the Java code
       embedded in a JSP page should import all the classes
       and interfaces used in the code

     – Note:- Directive elements doesn’t end with semi-colon!!
CS3002
Lecture 1 / Slide 40




   The page Directive - session

              The session attribute
                 Example

                <%@ page session = “false” %>

             By default, the generated Servlet creates a HttpSession object
             called session
             Setting session = “false” prevents the creation of this object
             The implicit object, session, is available only if this value is not set to
             false
             The value of this attribute can be set to false if the Servlet is not
             tracking the session
CS3002
Lecture 1 / Slide 41




   The page Directive - contentType
        The contentType attribute
             Example

    <%@ page contentType = “text/plain” %>

             The contentType of the response can be set using
             the appropriate MIME type
             The default value is “text/html”
CS3002
Lecture 1 / Slide 42




   The page Directive - errorPage

       The errorPage attribute
            Example

           <%@ page errorPage = “Error.jsp” %>

     – In case of any error, the user will be forwarded to Error.jsp.
     Error.jsp has the attribute isErrorPage set to true.
     – The exception object will be set as an attribute in the request
       object so that the Error.jsp can also access the exception
       object
CS3002
Lecture 1 / Slide 43




   The page Directive - isErrorPage

            The isErrorPage attribute
              – Example


                 <%@ page isErrorPage = “true” %>

     Error pages like Error.jsp in the previous example should contain this
     tag
     The presence of this tag creates a new Throwable object called
     exception in the generated Servlet
     The exception generated in the original page and passed as an
     attribute of the request will be assigned to this
     So, exception is an implicit object that we can use only in error pages
CS3002
Lecture 1 / Slide 44




   The page Directive - errorPage and isErrorPage
       Ex: ErrorTestPageJSP
       ErrorPageJSP
CS3002
Lecture 1 / Slide 45




   The include Directive
           The include directive can be used to include the
           contents of some other file in a JSP
                Example

    <%@ include file = "../Header.html" %>

         The contents of the included file will be pasted as a part of
         the JSP
         The contents can be static (HTML Page) or dynamic
         (Another JSP)
         The contents of a page can thus be separated into more
         manageable elements
CS3002
Lecture 1 / Slide 46

   The include Directive
       Many dynamic pages contain common static parts in
       them, mostly header and footer
       The common static parts can be stored as HTML files
       that can be included in a JSP
       Ex: IncludeTestJSP
       IncludeMeJSP
       Header.html
       Footer.html
CS3002
Lecture 1 / Slide 47




   The taglib Directive
       The taglib directive will be discussed later in the topic Custom
       Actions
       Example:
       <%@ taglib prefix="blx" uri=“/blx.tld" %>
       The "uri" specifies where to find the tag library
       description. The "prefix" is unique for the tag library. This
       directive is shows that we are using the tags in this library by
       starting them with blx:
CS3002
Lecture 1 / Slide 48




   Action tags
   ACTION TAGS are three types

                       FORWARD ACTION

                       INCLUDE ACTION

                       USEBEAN ACTION
CS3002
Lecture 1 / Slide 49




   Action Elements
       Action elements are tags that affect the runtime
       behavior of a JSP
       Action elements are also known as Standard Actions
       Some common standard actions are
            <jsp:forward>
            <jsp:include>
            <jsp:useBean>
            <jsp:setProperty>
            <jsp:getProperty>
            <jsp:param>
CS3002
Lecture 1 / Slide 50




   Standard Actions - jsp:forward
        The <jsp:forward> tag is used to forward a request to
        another page
        The control will be given to the target page
        The syntax of the tag is as follows
        Static url or computed at request time.
               <jsp:forward page = “Relative url” />

              <jsp:forward page = “<%=java expression %>” />

           We can pass parameters to the forwarded page using <jsp:param> tag
           The syntax of using the jsp:param tag is as follows

                <jsp:forward page = “url”>
                       <jsp:param name = “name” value = “value” />
                </jsp:forward>
CS3002
Lecture 1 / Slide 51




   Standard Actions - jsp:forward

       Ex: BusinessLogicJSPForm.html
       BusinessLogicJSP
       PresentationJSP
CS3002
Lecture 1 / Slide 52




   Standard Actions - jsp:include
      The <jsp:include> tag is used to include the contents of
      another file in a JSP
      The syntax of the tag is as follows
             <jsp:include page = “Relative url” />

         Unlike the include page directive that pastes the contents
         of the included file as a part of the JSP, the <jsp:include>
         tag acts at run time i.e., This action inserts the file at the time
         the page is requested but not at the time the JSP page is
         translated into a servlet as like Action Directives
         If the included file is modified, the next request will receive
         the modified content in the case of <jsp:include>
         EX: MyCompanyHome, StockPrice
CS3002
Lecture 1 / Slide 53




   why java beans in jsp
       A JavaBean can be defined as a reusable software component
       write a JavaBean that can then be used in a variety of other Java
       based softwares such as applications, Servlets or JSP pages.
       we can define our business logic within a JavaBean and then
       consistently use that logic in seperate applications.
       3 ways of writing code to be used by a JSP. These are,
       1. Place the code at the start of a JSP in a declaration,
       2. Use an include statement to reference another file which
       contains the code and now
       3. Package the code in a JavaBean (JavaBeans you can fully
       separate the business logic from the generation of the display.)
CS3002
Lecture 1 / Slide 54


   Standard Actions - jsp:useBean, jsp:setProperty,
   jsp:getProperty
   Minimizing Java code in a JSP will enable even a web
   designer to maintain it
   To separate presentation from code, we can encapsulate the
   logic in a JavaBean
   JSP can instantiate a JavaBean using the <jsp:useBean> tag,
   set the bean properties using the <jsp:setProperty> tag and
   get the bean properties using the <jsp:getProperty> tag
syntax:
<jsp:useBean id="name" class="package.class" />
Attributes: id, class, scope, type, beanName
scope: page | request | session | application
CS3002
Lecture 1 / Slide 55




   Bean Class
   package hall;
   public class SimpleBean
   {
      private String message = “Hello, Chakradhar";

         public String getMessage()
         { return(message); }

         public void setMessage(String message)
         { this.message = message; }
   }
CS3002
Lecture 1 / Slide 56




   Bean laws
    public no-arg constructor
    public getter and setter methods. “get” and “set” followed
    by same word. property name is derived by changing first
    character to lowercase.
    Setter argument type and getter return type must be identical
    You have a property because you have getter and setter
    methods
    For use with JSPs property type should be String or
    primitive. If it isn’t you can’t rely on standard actions and
    you might have to use scripting
CS3002
Lecture 1 / Slide 57




   UseBean Action
<HTML><BODY>
<jsp:useBean id="test” class="hall.SimpleBean" />
<jsp:setProperty name="test” property="message“ value="Hello WWW"
   />
<H1> Message:
<jsp:getProperty name="test“ property="message" />
</H1>
</BODY></HTML>
CS3002
Lecture 1 / Slide 58




   The WishBean

       Ex: WishBean
CS3002
Lecture 1 / Slide 59




   Standard Actions - jsp:useBean
       The <jsp:useBean> tag can be used to create a bean
       object
       The important attributes of <jsp:useBean> tag are
         id
         class
         scope
       The id attribute
         Specifies the name of the Bean object
       The class attribute
         Specifies the fully qualified name of the Bean class
CS3002
Lecture 1 / Slide 60


   Standard Actions - jsp:useBean
       The scope attribute
         Specifies the scope of the Bean object as page, request,
         session or application
       The page scope
         Available only for this request and only in this page
         By default, the scope will be page
       The request scope
         Available only for this request
         Available to other forwarded and included JSPs
       The session scope
         Available to the current session
       The application scope
         Available to any JSP in the same application
CS3002
Lecture 1 / Slide 61




   Standard Actions - jsp:useBean
       The <jsp:useBean> tag for instantiating the WishBean
       is as follows
     <jsp:useBean id = "myWishBean" class =
     “mypackage.WishBean"/>


            The above tag is equivalent to the following Java code




mypackage.WishBean myWishBean = new mypackage.WishBean();
CS3002
Lecture 1 / Slide 62


  jsp:setProperty
  It is used to sets values to properties of beans in two ways
  1. use it after, but outside of a jsp:useBean element, which is
       executed regardless of whether a new bean was instantiated or an
       existing bean was found.
  <jsp:useBean id="myName" .../ >...
  <jsp:setProperty name="myName” property=“anyProperty”… />

  2. appears inside the body of a jsp:useBean element, which is
      executed only if a new object was instantiated, not if an existing
      one was found.
  <jsp:useBean id="myName" ... > ...
      <jsp:setProperty name="myName” property=“anyProperty”… />
  </jsp:useBean>
CS3002
Lecture 1 / Slide 63




   Standard Actions - jsp:setProperty
       The <jsp:setProperty> tag can be used to set the Bean
       properties
       The attributes are
            name
            property
            param
            value
       The name attribute
            Specifies the id of the Bean object
CS3002
Lecture 1 / Slide 64


   Standard Actions - jsp:setProperty
      The property attribute
           Specifies the name of the bean property that is to be set
           If this attribute is *, all the request parameters will be
           assigned to bean properties based on matching name
           If the request parameter is having a value “”, the bean
           property is left unaltered
      The param attribute
           Specifies the name of the request parameter whose value is to
           be put in to the bean property
           If this value is not specified, the value of the request
           parameter whose name is same as that of the bean property
           will be assigned to the bean property
CS3002
Lecture 1 / Slide 65




   <jsp:setProperty>
   <jsp:useBean … >
       <jsp:setProperty name=”person” property=”name” param=”username” />
   </jsp:useBean>


    <input type=”text” name=”name”>
   <jsp:useBean … >
       <jsp:setProperty name=”person” property=”name” />
   </jsp:useBean>


   If ALL the request parameter names match with the bean property names then
   <jsp:useBean … >
       <jsp:setProperty name=”person” property=”*” />
   </jsp:useBean>
CS3002
Lecture 1 / Slide 66




   Standard Actions - jsp:setProperty
       The value attribute
            Specifies the value to be assigned to the bean property
         <jsp:setProperty name=“myWishBean”
         property=“wish” value=“Welcome” />

         The above tag is equivalent to the following Java code
        myWishBean.setWish(“Welcome”);
            A tag cannot have both param and value attributes together
       The <jsp:setProperty tag to set the bean property wish
       of WishBean to the value Welcome is as follows
CS3002
Lecture 1 / Slide 67




   <jsp:setProperty>
String to primitive doesn’t work with following
<jsp:setProperty name=”person” property=”empID”
   value=”<%=request.getParameter(“empID”)%>” />

But works with
<jsp:setProperty name=”person” property=”*” />
<jsp:setProperty name=”person” property=”empID” />
<jsp:setProperty name=”person” property=”empID” value=”343” />
<jsp:setProperty name=”person” property=”empID” param=”empID” />
CS3002
Lecture 1 / Slide 68


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

         The two required attributes are name of a bean, and
         property whose value should be inserted.

   <jsp:useBean id="itemBean" ... />...
   <UL>
   <LI>Number of items:
   <jsp:getProperty name="itemBean" property="numItems" />
   <LI>Cost of each:
   <jsp:getProperty name="itemBean" property="unitCost" />
   </UL>
CS3002
Lecture 1 / Slide 69




   Standard Actions - jsp:getProperty
       The <jsp:getProperty> tag can be used to get the value
       of a bean property
       The attributes are
            name
            property
       The name attribute
            Specifies the id of the Bean object
       The property attribute
            Specifies the name of the bean property to get
CS3002
Lecture 1 / Slide 70


   Standard Actions - jsp:getProperty
       The <jsp:getProperty> can be used to get the property
       wish of the WishBean as follows
               <jsp:getProperty name =
               "myWishBean" property = "wish" />
             The above tag is equivalent to the following Java
             code

                 myWishBean.getWish();
CS3002
Lecture 1 / Slide 71


   Standard Actions - jsp:useBean,
   jsp:setProperty, jsp:getProperty
       Ex: BeanTagTestJSP
CS3002
Lecture 1 / Slide 72


   Standard Actions - jsp:useBean,
   jsp:setProperty, jsp:getProperty
       Ex: Employee
       EmployeeBeanTestJSPForm.html
       EmployeeBeanTestJSP
CS3002
Lecture 1 / Slide 73




   Setting attributes at various scopes
                Servlet                               JSP
Application     getServletContext().                  application.setAttribute(“foo”,barObj);
                setAttribute(“foo”,barObj);
Request         request.setAttribute(“foo”,barObj);   request.setAttribute(“foo”,barObj);
Session         request.getSession().                 session.setAttribute( “foo”,barObj);
                setAttribute(“foo”,barObj);
Page            Does not apply                        pageContext.setAttribute(“foo”,barObj);

 PageContext       extends JspContext
 APPLICATION_SCOPE               //static final fields
 PAGE_SCOPE
 REQUEST_SCOPE
 SESSION_SCOPE
 Methods of JspContext
 getAttribute(String name, int scope)
 setAttribute(String name,Object obj,int scope)
CS3002
Lecture 1 / Slide 74




   Custom Actions
       In JSP, the programmer can create her own customized
       tags to encapsulate code from presentation
       These tags are categorized as Custom Actions
       The syntax of using custom actions is as follows

                <prefix:name />

           Each custom tag will have an implementation class
           where the actual Java code resides
           When the JSP Container comes across a custom tag,
           the code in the implementation class is executed
           However, the code will be hidden from the JSP page
CS3002
Lecture 1 / Slide 75




   The Tag interface

        The implementation class of a custom tag should
        implement javax.servlet.jsp.jspext.Tag interface
        Two important methods of the Tag interface are as
        follows
public int doStartTag() throws javax.servlet.jsp.JspException
public int doEndTag() throws javax.servlet.jsp.JspException
public int doAfterBody() throws javax.servelt.jsp.JspException

             These methods are automatically executed when the
             JSP encounters the starting tag and ending tag of the
             custom tag
CS3002
Lecture 1 / Slide 76



   Tag handler execution
CS3002
Lecture 1 / Slide 77


   The Tag interface
      The Tag interface has the following final static int fields
              EVAL_BODY_INCLUDE      SKIP_BODY
              EVAL_PAGE              SKIP_PAGE
              EVAL_BODY_AGAIN


        The doStartTag() method can return
         – EVAL_BODY_INLCUDE so that JSP continues evaluating the body of
           the tag
         – SKIP_BODY so that JSP skips evaluating the body of the tag
        The doEndTag() method can return
         – EVAL_PAGE so that JSP continues evaluating the rest of the page
         – SKIP_PAGE so that JSP skips evaluating the rest of the page
        The doAfterBody() method can return
         – EVAL_BODY_AGAIN so that JSP continues evaluating the body of
           the tag
         – SKIP_BODY so that JSP skips evaluating the body of the tag
CS3002
Lecture 1 / Slide 78




   The TagSupport class
       The TagSupport class implements the Tag interface
       and provides blank implementation for all the methods
       It is easy to extend TagSupport than to implement Tag
       The doStartTag(), doAfterBody() and doEndTag()
       methods of TagSupport class return SKIP_BODY,
       SKIP_BODY and EVAL_PAGE respectively.
CS3002
Lecture 1 / Slide 79


   The PageContext class
       A protected object of type javax.servlet.jsp.PageContext
       called pageContext is declared in the TagSupport class
       This object can be used to get many attributes of the
       page like the out, response, request and session objects
       Eg: JspWriter out= pageContext.getOut();
       Some important methods of the PageContext class is as
       follows
       public abstract JspWriter getOut()
       public abstract ServletRequest getRequest()
       public abstract ServletResponse getResponse()
       public abstract HttpSession getSession()
CS3002
Lecture 1 / Slide 80
                                                 Tag handler class
  .tld file                                      public class SimpleTagTest1 extends
<taglib >                                           TagSupport {
    <tlib-version>1.2</tlib-version>                private List movieList;
    <uri>simpleTags</uri>                           public void setMovieList(List
    <tag>                                           movieList) {
     <description> simple </description>                 this.movieList=movieList;
     <name>simple1</name>                           }
     <tag-class>foo.SimpleTagTest1</tag-class>      public void doStartTag throws
     <body-content>empty</body-content>             JSPException{
     <attribute>                                         try {
           <name>movieList</name>                        Iterator i= movieList.iterator();
           <required>true</required>                     for …
           <rtexprvalue>true</rtexprvalue>               } catch(IOException e) {
     </attribute>                                throw new
                                                    JspException(“IO”+e.toString());
    </tag>
                                                         }
                                                    }}
CS3002
Lecture 1 / Slide 81




   The helloworld Custom Tag

       Ex: HelloWorld
CS3002
Lecture 1 / Slide 82




   The taglib Directive
            Tag Library Descriptor or TLD is an xml file that
            describes a custom tag
            Ex: HelloWorldTag.tld
            The taglib directive is used to tell the JSP the location
            of TLD
    <%@ taglib uri=“HelloWorldTag.tld" prefix="tagexample" %>

                 tagdir=“/WEB-
     <%@ taglib tagdir=“/WEB-INF/tlds/HelloWorldTag.tld"
     prefix="tagexample" %> used in a JSP as follows
          The custom tag can be
              <tagexample:helloworld />
CS3002
Lecture 1 / Slide 83




   The helloworld Custom Tag

       Ex: HelloWorldTagTestJSP
CS3002
Lecture 1 / Slide 84




   The emplist Custom Tag

       Ex: EmpList
       EmpListTag.tld
       EmpListTagLibTestJSP
CS3002
Lecture 1 / Slide 85


   The hellouser Custom Tag
       Custom Tags can accept attributes and behave
       according to their value
       The TLD file should contain the information about
       these attributes
       Ex: HelloUser
       HelloUserTag.tld
       HelloUserTagLibTestJSP
CS3002
Lecture 1 / Slide 86




   Expression Language
      EL makes nested properties easy to print.
      JSP supports Expression Language to create a “scriptless”
      JSP
               ${param.name}
      Expression Language or EL provides simpler syntax and
      implicit objects to perform some of the actions that could
      be performed by scriptlets
– The above EL expression is equivalent to the following scriptlet
             request.getParameter(“name”)
CS3002
Lecture 1 / Slide 87


   EL implicit objects
            pageScope      //map of scope attirbutes
            requestScope
            sessionScope
            applicationScope
            param          // map of request parameters
            paramValues
            header         //map of request headers
            headerValues
            cookie
            initParam      //map of context init parameters, not servlet
            initParameters
            pageContext    //bean
CS3002
Lecture 1 / Slide 88


   EL
       ${person.name}         same as ${person[“name”] }
   Person can be bean or map. Name is property or key
       If person is array or list, above doesn’t work
   String[] favMusic= {“zero 7”,”tah 80”,” frou frou” };
   request.setAttribute(“musicList”, favMusic);
    If musicList refers to an array.
    First song: ${musicList[0]}            // ${musicList.0} doesn’t work
   Second song : ${musicList[“1”]}
       ${param.name}          ${paramValues.name[0]}
       ${request.method} //doesn’t works
       ${requestScope.method}          //works
       <content-param><param-name>..</..> <param-value> </..> </context-param>
         ${initParam.email}
       EL functions: ${param:fun()}
CS3002
Lecture 1 / Slide 89


  JSP Standard Tag Library - JSTL
    Many developers creating tag libraries were duplicating
    many actions as these libraries were created separately
    There was a need for standardizing the tag libraries, and JSP
    Standard Tag Library (JSTL) was created based on this
    JSTL provides a rich set of tags that helps the web designers
    to perform various actions like
         iterate over each item in a Collection
         format
         process xml
         access database
    Application programmers rarely create custom tags and
    instead use the powerful JSTL and other open source tag
    libraries
CS3002
Lecture 1 / Slide 90




<%@ taglib prefix=“c” uri=“http://java.sun.com/jstl/core”%>
<c:set var=“a” value=“sam” />
<c:out value=“${a}” />

String s=request.getParameter(“text1”);
same as
<c:set var=“s” value=“${param.text1}” >
CS3002
Lecture 1 / Slide 91




   JSTL tags
       Some absolute URIs are given for the JSTL library are as follows:
       For core: http://java.sun.com/jsp/jstl/core
       For XML: http://java.sun.com/jsp/jstl/xml
       For Internationalization(date format & currency format):
       http://java.sun.com/jsp/jstl/fmt
       For SQL: http://java.sun.com/jsp/jstl/sql
       For Functions: http://java.sun.com/jsp/jstl/functions


       core            <c:       />
       xml                   <xml:       />
       sql                   <sql:       />
       formatting                <fmt:        />
       functions                 <fn:    />
CS3002
Lecture 1 / Slide 92




   Core tags
       <c:set
       <c:out
       <c:if
       <c:choose, <c:when ,   <c:otherwise
       <c:foreach
       <c:forTokens
       <c:import
       <c:url
       <c:redirect
       <c:param
CS3002
Lecture 1 / Slide 93

   <c:if>
   <%@ page contentType="text/html" %>
   <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
   <html><body>
   <form method=post action=demo3.jsp>
        <select       name="combo1">
              <option     value="sam">sam
              <option     value="tom">tom
        </select>
       <input type=submit>
   </form>
   <c:set        var="s" value="${param.combo1}"     />
   <c:out value="${s}"       /> <br>
   <c:if test="${s eq 'sam' }" >
        <c:out   value="Good Morning...SAM!" />
   </c:if>
   <c:if test="${s = = 'tom'}"      >
        <c:out value=" How Are You?....TOM!" />
   </c:if> </body> </html>
CS3002
Lecture 1 / Slide 94

    <c:choose., <c:when>                 ,     <c:otherwise>
  <%@ page contentType="text/html" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
  <html> <body bgcolor=lightblue>
      <form method=post action="demo3.jsp">
      <select name="combo1">
        <option value="1">1 </option>  <option value="2">2 </option>
        <option value="3">3 </option>   <option value="4">4 </option>
        <option value="5">5 </option>   <option value="7">7 </option>
      </select>
    <input type=submit>
       <c:set var="s" value="${param.combo1}" />
        Today is <font size=24 color=red>
  <c:choose>
      <c:when      test="${s==1}">Sunday </c:when>
      <c:when     test="${s==2}">Monday</c:when>
      <c:when     test="${s==3}">Tuesday</c:when>
      <c:when     test="${s==4}">Wednesday</c:when>
      <c:when     test="${s==5}">Thursday</c:when>
   <c:otherwise> select between 1 & 5        </c:otherwise>
      </c:choose> </body> </html>
CS3002
Lecture 1 / Slide 95


   <c:forEach>
   <c:forEach> action tag contain the following attribute list:
   items : the collection of items like String[]
   var : a symbolic name for the collection
   begin : the starting index of iteration
   end : the ending index of iteration
   step : incremental step
   varStatus: symbolic name for current status.
   <%@ page contentType="text/html" %>
     <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
     <c:forEach var="n" begin="3" end="8" >
       <c:out value="${n}" /> <br>
     </c:forEach>
CS3002
Lecture 1 / Slide 96




   <c:import>
   <%@ taglib     prefix="c" uri="http://java.sun.com/jstl/core" %>
     <c:import url="welcome.htm"/>
     <c:out value="to our web-site!" />
CS3002
Lecture 1 / Slide 97




   <c:url>
   <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
     <a href= "<c:url value="http://localhost:8080/welcome.htm/>">
     send </a>


       Url encoding
CS3002
Lecture 1 / Slide 98


   <c:redirect>
        <%@ page contentType="text/html" %>
        <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
        <c:redirect url="http://localhost:8080/welcome.htm />
        Redirecting to the url
        <%@ page contentType="text/html" %>
        <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
        <c:redirect url="http://localhost:8080/jstldemos/core/sample.jsp" >
              <c:param name="name1" value="SAM"/>
        </c:redirect>
        passing parameters to sample.jsp
        sample.jsp
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
      <c:out value="${param.name1}"/>
CS3002
Lecture 1 / Slide 99




   books.xml
       <?xml version="1.0" ?>
       <books>
            <book>
              <title>cobol</title>
              <author>roy</author>
         </book>
         <book>
              <title>java</title>
              <author>herbert</author>
         </book>
         <book>
              <title>xml unleashed</title>
              <author>morrison</author>
         </book>
        </books>
CS3002
Lecture 1 / Slide 100
    JSTL- XML
   <%@ page contentType="text/html" %>
      <%@ taglib     prefix="c" uri="http://java.sun.com/jstl/core" %>
      <%@ taglib     prefix=“x" >uri="http://java.sun.com/jstl/xml" %>
       <html> <body>
       <c:import url="books.xml" var="url" />
       <x:parse     xml="${url}" var="doc" />
       <table border=1> <th> <tr> <td>title</td>       <td>author</td> </tr> </th>
       <x:forEach var="n" select="$doc/books/book">
          <tr>
              <td> <x:out select="$n/title" /></td>
              <td> <x:out select="$n/author" /></td>
          </tr>                                      Title                     Author
       </x:forEach>                                  Cobol                     Roy
       </table> </body> </html>                      Java                      Herbert
        We have given a symbolic name for this file as 'url‘   Xml unleashed   morrison
       The resulting tree is given a symbolic name as 'doc'.
       Magically, we have parsed a given XML document and extracted information,
       without any mention about DOM,SAX and such words.
CS3002
Lecture 1 / Slide 101
   students.xml
 <?xml version="1.0"?>
 <students>
      <student>
         <name>Thomas</name>
         <place>Delhi</place>
         <number>1111</number>
         <mark>78</mark>
       </student>
    <student>
          <name>David</name>
          <place>Bombay</place>
          <number>4444</number>
          <mark>90</mark>
        </student>
 </students>
CS3002
Lecture 1 / Slide 102




   xsl1.xsl
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
    <html> <body> <table border="2" bgcolor="yellow">
    <tr> <th>Name</th> <th>Place</th> <th>Number</th> <th>Mark</th> </tr>
     <xsl:for-each select="students/student">
       <tr>
        <td><xsl:value-of select="name"/> </td>
        <td><xsl:value-of select="place"/> </td>
        <td><xsl:value-of select="number"/> </td>
        <td><xsl:value-of select="mark"/> </td>
       </tr>
    </xsl:for-each>
   </table> </body> </html>
   </xsl:template>
   </xsl:stylesheet>
CS3002
Lecture 1 / Slide 103




   Transforming xml to xsl using JSTL
   <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
     <%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
     <c:import url="students.xml" var="url" />
     <c:import url="xsl1.xsl" var="xsl" />
     <x:transform xml="${url}" xslt="${xsl}" />
CS3002
Lecture 1 / Slide 104




   JSTL sql tags
       <html>
       <body>
       <form method=post action="query.jsp">
       <textarea name='area1' rows=10 cols=30>
       </textarea>
       <input type=submit>
       </form>
       </body>
       </html>
CS3002
Lecture 1 / Slide 105

  query.jsp
  <%@ taglib  prefix="c" %>uri="http://java.sun.com/jstl/core"
    <%@ taglib prefix="sql" %> uri="http://java.sun.com/jstl/sql"
  <html> <body>
  <sql:setDataSource var="db"
         driver="sun.jdbc.odbc.JdbcOdbcDriver"
         url="jdbc:odbc:dbdemo" />
     <c:set var='s' value="${param.area1}" />
     <c:out value="${s}" /> <br>
     <sql:query var="query1" dataSource="${db}" sql="${s}"          />
     <table border="1">
      <c:forEach var="row" items="${query1.rows}" >
     <tr>
       <td> <c:out value="${row.name}" /></td>
       <td> <c:out value="${row.place}" /></td>
     </tr>
     </c:forEach> </table> </body> </html>
CS3002
Lecture 1 / Slide 106




   Function tags
       <c:out value="${fn:replace(string,find,replaceWith)}"/>
       <c:out value="${fn:indexOf(text,str)}"/>
       <c:forEach var="num" items="${fn:split(str1, ' ')}">
            <c:out value="${num}" />
       </c:forEach>
       <c:out value="${fn:substring(string,start,end)}"/>
       <c:out value="${fn:substringBefore(fString,sString)}"/>
       <c:out value="${fn:substringAfter(fString,sString)}"/>
       <c:set var="trimText" value="${fn:trim(text)}"/>
CS3002
Lecture 1 / Slide 107




   <fn:escapeXml(String)> Tag of JSTL
   <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
   <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
   <html> <head> <title>Example of fn:escapeXml Tag</title> </head> <body>
      <c:set var="str1" value="This is first String."/>
       <c:set var="str2" value="This <abc>is second String.</abc>"/>
       <c:set var="str3" value="<mahendra>This is first String.</mahendra>"/>
       <h4>fn:escapeXml</h4>
        <table border="1">
   <tr> <th>without fn:escapeXml</th> <th>with fn:escapeXml</th> </tr>
   <tr> <td>${str1}</td> <td> ${fn:escapeXml(str1)} </td> </tr>
   <tr> <td>${str2}</td> <td> ${fn:escapeXml(str2)} </td> </tr>
   <tr> <td>${str3}</td> <td> ${fn:escapeXml(str3)} </td> </tr>
   </table> </body> </html>
CS3002
Lecture 1 / Slide 108




   Summary
       JSP is a technology for coding the presentation logic of
       an enterprise application
       Web designers without programming skills can create
       and maintain JSP
       The Standard Actions and Custom Actions help to
       encapsulate the code from presentation
       Rich, Open Source, Standard Tag Libraries are
       available
CS3002
Lecture 1 / Slide 109


    References
     http://www.roseindia.net/jsp/
        http://www.roseindia.net/jstl/jstlxmltags.shtml
        http://www.roseindia.net/jstl/jstsqlltags.shtml
        http://www.roseindia.net/jsp/implement-javascript-with-jsp.shtml
        http://www.roseindia.net/jsp/loginbean.shtml
        http://www.roseindia.net/jsp/loginstatus.shtml
        http://www.roseindia.net/jsp/DisplayimageonJSPpageusingXML.shtml
        http://www.roseindia.net/jsp/ExampleOfPrintingTextMessage.shtml
        http://www.roseindia.net/jsp/embeddingwmp.shtml
        http://www.roseindia.net/jsp/core-xml-tag.shtml
        http://www.roseindia.net/jsp/parsing-xml.shtml
        http://www.roseindia.net/jsp/applet-jsp.shtml
        http://www.roseindia.net/jsp/add-flash-jsp.shtml
        http://www.gulland.com/courses/JavaServerPages/jsp_beans.jsp
CS3002
Lecture 1 / Slide 110




   Applications
       http://www.roseindia.net/jsp/bank.shtml
       http://www.roseindia.net/jsp/online-quiz-application-
       jsp.shtml
       http://www.roseindia.net/jsp/paging.shtml
       http://www.roseindia.net/jsp/file_upload/uploadingMul
       tipleFiles.shtml
       http://www.roseindia.net/jsp/jsp-frameset.shtml

More Related Content

What's hot (16)

Java script
Java scriptJava script
Java script
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
Servlet and jsp interview questions
Servlet and jsp interview questionsServlet and jsp interview questions
Servlet and jsp interview questions
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
 
p032-26
p032-26p032-26
p032-26
 
Wt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side frameworkWt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side framework
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Jsp
JspJsp
Jsp
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
 
Jsp
JspJsp
Jsp
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-Challenges
 
10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 

Similar to CS3002 Lecture 1: Introduction to Servlets and JSPs

Similar to CS3002 Lecture 1: Introduction to Servlets and JSPs (20)

Jsp
JspJsp
Jsp
 
Introduction to JSP.pptx
Introduction to JSP.pptxIntroduction to JSP.pptx
Introduction to JSP.pptx
 
Struts 2 Overview
Struts 2 OverviewStruts 2 Overview
Struts 2 Overview
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
C:\fakepath\jsp01
C:\fakepath\jsp01C:\fakepath\jsp01
C:\fakepath\jsp01
 
Ibm
IbmIbm
Ibm
 
PPT on javascript ajax and css and some points related to server
PPT on javascript ajax and css and some points related to serverPPT on javascript ajax and css and some points related to server
PPT on javascript ajax and css and some points related to server
 
Transformation of Java Server Pages: A Modern Approach
Transformation of Java Server Pages: A Modern ApproachTransformation of Java Server Pages: A Modern Approach
Transformation of Java Server Pages: A Modern Approach
 
Java .ppt
Java .pptJava .ppt
Java .ppt
 
25.ppt
25.ppt25.ppt
25.ppt
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp interview questions by java training center
Jsp interview questions by java training centerJsp interview questions by java training center
Jsp interview questions by java training center
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
Jsp 01
Jsp 01Jsp 01
Jsp 01
 
The java server pages
The java server pagesThe java server pages
The java server pages
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Session 36 - JSP - Part 1
Session 36 - JSP - Part 1Session 36 - JSP - Part 1
Session 36 - JSP - Part 1
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp
JspJsp
Jsp
 

Recently uploaded

Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 

Recently uploaded (20)

Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 

CS3002 Lecture 1: Introduction to Servlets and JSPs

  • 1. CS3002 Lecture 1 / Slide 1 CS3002 Software Technologies Lecture 12
  • 2. CS3002 Lecture 1 / Slide 2 Responsibilities of Servlets Coding the presentation logic and business logic together is not a good practice A change in any one of these requires the modification of the entire code Programmers with different skill sets are required for creating and maintaining these Servlets, being Java programs, are best suited for coding business logic
  • 3. CS3002 Lecture 1 / Slide 3 Responsibilities of Servlets Servlets are not suitable to code presentation logic It is not easy to mix static contents with dynamic contents in Servlets As Servlets are not as easy as HTML, it will be difficult for web designers to use this technology A technology with the power of Servlets and ease of HTML is required to code presentation logic, so that web designers can also easily use it
  • 4. CS3002 Lecture 1 / Slide 4 JSP JSP or JavaServer Pages is a technology developed by Sun Microsystems for coding the presentation layer of an enterprise application A JSP file is very similar to an HTML file Unlike HTML files, JSP files will contain some Java code also with in <% %> tags Ex: LongMessageJSP
  • 5. CS3002 Lecture 1 / Slide 5 JSP When a client requests for a JSP, the Server (For example, Tomcat), sends the HTML tags as such to the browser The code between <% and %> will be compiled, executed and the output will be send to the browser JSP Can be used to code presentation logic Can be used to generate dynamic pages Is as simple as HTML, even web designers can use it easily
  • 6. CS3002 Lecture 1 / Slide 6 Servlets Vs JSP Servlet Bits of HTML embedded in Java code Suitable for coding the business layer of an enterprise application Created and maintained by Java programmers JSP Bits of Java code embedded in HTML Suitable for coding the presentation layer of an enterprise application Created and maintained by web designers
  • 7. CS3002 Lecture 1 / Slide 7 JSP Internally, the JSP is getting converted to a Servlet When a user requests for a .jsp file for the first time, the JSP Container will create a Servlet that would produce the output that the .jsp file is supposed to produce The Servlet is compiled, run and the output is given to the browser Starting from the second request, there is no overhead of compilation IS CLIEN Request JSP VALID No T ? Text COMPILE Response SERVLET Yes Class
  • 8. CS3002 Lecture 1 / Slide 8 JSP Ex: LongMessageJSP_jsp.java In Netbeans its found under, Webapplication folder -> build -> generated -> src -> org -> apache -> jsp -> LongMessageJSP_jsp.java
  • 9. CS3002 Lecture 1 / Slide 9 Implicit Objects some implicit objects A JSP developer can use Some of the important objects and their classes are as follows out - JSPWriter request - HttpServletRequest response- HttpServletResponse session - HttpSession application - ServletContext config - ServletConfig exception - Throwable / JspException pageContext- PageContext page - Object These objects will be declared by the generated Servlet and hence the statements we write in JSP using these variables will get a meaning once they are pasted in the Servlet code
  • 10. CS3002 Lecture 1 / Slide 10 Directives //no output to client page include taglib Scripting elements Scriptlet Declaration expression Standard actions forward include useBean
  • 11. CS3002 Lecture 1 / Slide 11 Implicit Objects - Example This example uses the out, request and session objects Ex: SessionTestJSPForm.html SessionTestJSP ReadSessionTestJSP
  • 12. CS3002 Lecture 1 / Slide 12 JSP tags SCRIPTING TAGS DIRECTIVE TAGS ACTION TAGS CUSTOM TAGS
  • 13. CS3002 Lecture 1 / Slide 13 Tags in JSP Tags in JSP can be categorized as Comments Scripting elements Directive elements Action elements Template data – Any thing other than the above mentioned four categories fall under template data – This will include all HTML tags and text
  • 14. CS3002 Lecture 1 / Slide 14 Comments Just like any other HTML tag, standard HTML comment tag also can be used in JSP <!-- <!-- This is a comment in HTML --> --> This comment tag will reach the browser A JSP specific comment tag is written as follows <%-- <%-- This is a JSP Comment --%> --%> This comment tag will not reach the browser
  • 15. CS3002 Lecture 1 / Slide 15 Character quoting conventions To get “<%” character in text (static HTML) <% To get “%>” character in scripting elements %> To get a single quote in an attribute ' To get a double quote in an attribute "
  • 16. CS3002 Lecture 1 / Slide 16 Scripting tags SCRIPTING TAGS are three types SCRIPTLET TAGS EXPRESSION TAGS DECLARATION TAGS
  • 17. CS3002 Lecture 1 / Slide 17 Scripting Elements Scripting elements are elements in the page that include the Java code JSP can contain 3 types of scripting elements Scriptlets <% %> Declarations <%! %> Expressions <%= %>
  • 18. CS3002 Lecture 1 / Slide 18 Scripting Elements - Scriptlets The Java statements that appear between <% and %> are called scriptlets This code goes to _jspService() method of servlet Java statements end in semicolon Ex: TestJSP
  • 19. CS3002 Lecture 1 / Slide 19 Scripting Elements - Declaration of variables Variables declared within <% and %> will be local to the service method of the generated Servlet and each request will have a separate copy of this variable <% int data; %> Declarative tag Variables declared within <%! and %> will be a data member of the generated Servlet class and all the requests will use the same copy of this variable <%! double amount; %>
  • 20. CS3002 Lecture 1 / Slide 20 Scripting Elements - Declaration of methods Methods also can be declared using scripting elements All variables and methods should be declared within <%! and %> and they become a method of the generated Servlet Ex: MethodTestJSPForm.html MethodTestJSP
  • 21. CS3002 Lecture 1 / Slide 21 Declaration tag <html><body> <%! int addNum(int n, int m) { return n + m; } int subtractNum(int N1, int N2) { return N1 - N2; } %> <% out.println("6 + 2 = " + addNum(6, 2)); %> <% out.println("8 - 5 = " + subtractNum(8, 5) + "<BR>"); </body></html>
  • 22. CS3002 Lecture 1 / Slide 22 Handling form in jsp <html> <head><title>Using Post Method in JSP Form.</title></head> <body> <form method="post"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td>Enter your name: </td> <td><input type="text" size="20" name="txtName" /></td> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="B1" value="Submit" /> <input type="reset" name="B2" value= "Reset" /></td> </tr> </table> </form> <% if(request.getParameter("txtName") != null) { if(request.getParameter("txtName"). equals("")) out.println("<html><font color=red>Please enter your name.</font></html>"); else out.println("Your username is: " + request.getParameter("txtName")); } %> </body> </html>
  • 23. CS3002 Lecture 1 / Slide 23 Validating using javascript in jsp …. <% if(ent==0) String insertQry = "insert Employee values('"+code+"','"+empname+"')"; int val = stmt.executeUpdate(insertQry); %> <script language="javascript"> alert("Insertion successful"); document.location="EmplyeeInformation.jsp"; </script> <% } if(ent==1) { %> <script language="javascript"> alert("This Emp ID already Exists"); document.location="EmplyeeInformation.jsp"; </script> <% } stmt.close(); con.close(); } catch(Exception e) { out.println(e.toString()); } %>
  • 24. CS3002 Lecture 1 / Slide 24 Initialization parameters <servlet> <servlet-name>MyTestInit</servlet-name> <jsp-file>/TestInit.jsp</jsp-file> <init-param> <param-value>name</param-name> <param-value>abc</param-value> </init-param> </servlet> web.xml
  • 25. CS3002 Lecture 1 / Slide 25 Scripting Elements - Declaration of JSP Lifecycle methods The code that should be executed only once when the JSP is invoked for the first time can be coded in a method jspInit() The jspInit() method will be executed only once per JSP, not per request Typically this method contains code for initialization The code that should be executed only once when the JSP is unloaded from the memory can be coded in a method jspDestroy() Typically this method contains code to cleanup the resources used by the JSP
  • 26. CS3002 Lecture 1 / Slide 26 JSP Lifecycle javax.servlet.jsp.JspPage methods jspInit(), jspDestroy() javax.servlet.jsp.HttpJspPage extends javax.servlet.jsp.JspPage methods _ jspService(HttpServletRequest,HttpServletResponse) // can’t override this!!! Ex: LifecycleTestJSPForm.html, LifecycleTestJSP
  • 27. CS3002 Lecture 1 / Slide 27 Scripting Elements - Expressions The value of an expression can be printed to the browser using the syntax <%=expression%> <% String name = “Software”; %> Hello <%=name%> These expressions doesn’t end with semi-colon. These are passed as argument to out.print()
  • 28. CS3002 Lecture 1 / Slide 28 Access all the fields from table through JSP <% String QueryString = "SELECT * from stu_info"; rs = statement.executeQuery(QueryString); %> <TABLE cellpadding="15" border="1" style="background- color: #ffffcc;"> <% while (rs.next()) { %> <TR> <TD> <%=rs.getInt(1)%> </TD> <TD><%=rs.getString(2)%> </TD> <TD> <%=rs.getString(3)%> </TD> <TD> <%=rs.getString(4)%> </TD> </TR> <% } %>
  • 29. CS3002 Lecture 1 / Slide 29 Servlet and JSP String sql = "select * from message"; Statement s = connection.createStatement(); s.executeQuery (sql); rs = s.getResultSet(); while (rs.next ()){ //Add records into data list dataList.add(rs.getInt("id")); dataList.add(rs.getString("message")); }….. request.setAttribute("data",dataList); RequestDispatcher dispatcher = request.getRequestDispatcher(DataPage.jsp); if (dispatcher != null){ dispatcher.forward(request, response); } DataPage.Jsp <body> <table border="1" width="303"> <tr><td width="119"><b>ID</b></td><td width="168"><b>Message</b></td></tr> <%Iterator itr;%> <% List data= (List)request.getAttribute("data"); for (itr=data.iterator(); itr.hasNext(); ) { %> <tr><td width="119"><%=itr.next()%></td><td width="168"><%=itr.next()%></td></tr> <%}%> </table></body>
  • 30. CS3002 Lecture 1 / Slide 30 Authentication <%@ page import="java.sql.*" %> <% String sql = "select user,password from User"; Statement s = connection.createStatement(); s.executeQuery (sql); rs = s.getResultSet(); while (rs.next ()){ userName=rs.getString("user"); passwrd=rs.getString("password"); } %> <% if(userName.equals(request.getParameter("user")) && passwrd.equals(request.getParameter("pass"))){ out.println("User Authenticated"); } else{ out.println("You are not an authentic person"); } %>
  • 31. CS3002 Lecture 1 / Slide 31 image <% psmnt = connection.prepareStatement("SELECT image FROM save_image WHERE id = ?"); psmnt.setString(1, "11"); // here integer number '11' is image id from the table rs = psmnt.executeQuery(); if(rs.next()) { byte[] bytearray = new byte[1048576]; int size=0; sImage = rs.getBinaryStream(1); response.reset(); response.setContentType("image/jpeg"); while((size=sImage.read(bytearray))!= -1 ){ response.getOutputStream().write(bytearray,0,size); } } %> save_image table CREATE TABLE save_image ( id int(5) NOT NULL auto_increment, name varchar(25) default NULL, city varchar(20) default NULL, image blob, Phone varchar(15) default NULL, PRIMARY KEY (`id`) );
  • 32. CS3002 Lecture 1 / Slide 32 Retrieving data from a file <%@ page import="java.io.*"%> <html><body> <% String fName = "c:csvmyfile.csv"; String thisLine; int count=0; int i=0; FileInputStream fis = new FileInputStream(fName); DataInputStream myInput = new DataInputStream(fis); %> <table> <% while ((thisLine = myInput.readLine()) != null) { String strar[] = thisLine.split(","); for(int j=0;j<strar.length;j++) { if(i!=0) { out.print(" " +strar[j]+ " "); } else { out.print(" <b>" +strar[j]+ "</b> "); } } out.println("<br>"); i++; } %> </table> </body> </html>
  • 33. CS3002 Lecture 1 / Slide 33 Export data to a file from database http://www.roseindia.net/jsp/jdbccsv.shtml Downloading a file from database http://www.roseindia.net/jsp/downloadcsv.shtml
  • 34. CS3002 Lecture 1 / Slide 34 Reading request information <%= request.getMethod() %> <%= request.getRequestURI() %> <%= request.getProtocol() %> <%= request.getQueryString() %> <%= request.getContentType() %> <%= request.getServerName() %> <%= request.getRemoteUser() %> …
  • 35. CS3002 Lecture 1 / Slide 35 Retrieving data posted to a jsp file from html file <input type=“text” name=“username” size=“20”> <html><body> <%=request.getParameter(“username”) %> </body></html>
  • 36. CS3002 Lecture 1 / Slide 36 Directive tags DIRECTIVE TAGS are three types PAGE DIRECTIVE INCLUDE DIRECTIVE TAGLIB DIRECTIVE
  • 37. CS3002 Lecture 1 / Slide 37 Directive Elements Directive elements provide information to the JSP container about the page JSP can contain three types of directives page include taglib Syntax <%@ directive attribute="value" %> <%@ directive attribute1="value1“ attribute2="value2“ ...attributeN="valueN" %>
  • 38. CS3002 Lecture 1 / Slide 38 The page Directive The page directive has the following form <%@ page attributes %> Some of the important attributes are import session contentType errorPage isErrorPage isThreadSafe, isELIgnored, language, extends, session, buffer, autoFlush, info, pageEncoding
  • 39. CS3002 Lecture 1 / Slide 39 The page Directive - import The import attribute – Example <%@ page import = “java.io.*,java.net.Socket” %> – Just like a normal Java program, the Java code embedded in a JSP page should import all the classes and interfaces used in the code – Note:- Directive elements doesn’t end with semi-colon!!
  • 40. CS3002 Lecture 1 / Slide 40 The page Directive - session The session attribute Example <%@ page session = “false” %> By default, the generated Servlet creates a HttpSession object called session Setting session = “false” prevents the creation of this object The implicit object, session, is available only if this value is not set to false The value of this attribute can be set to false if the Servlet is not tracking the session
  • 41. CS3002 Lecture 1 / Slide 41 The page Directive - contentType The contentType attribute Example <%@ page contentType = “text/plain” %> The contentType of the response can be set using the appropriate MIME type The default value is “text/html”
  • 42. CS3002 Lecture 1 / Slide 42 The page Directive - errorPage The errorPage attribute Example <%@ page errorPage = “Error.jsp” %> – In case of any error, the user will be forwarded to Error.jsp. Error.jsp has the attribute isErrorPage set to true. – The exception object will be set as an attribute in the request object so that the Error.jsp can also access the exception object
  • 43. CS3002 Lecture 1 / Slide 43 The page Directive - isErrorPage The isErrorPage attribute – Example <%@ page isErrorPage = “true” %> Error pages like Error.jsp in the previous example should contain this tag The presence of this tag creates a new Throwable object called exception in the generated Servlet The exception generated in the original page and passed as an attribute of the request will be assigned to this So, exception is an implicit object that we can use only in error pages
  • 44. CS3002 Lecture 1 / Slide 44 The page Directive - errorPage and isErrorPage Ex: ErrorTestPageJSP ErrorPageJSP
  • 45. CS3002 Lecture 1 / Slide 45 The include Directive The include directive can be used to include the contents of some other file in a JSP Example <%@ include file = "../Header.html" %> The contents of the included file will be pasted as a part of the JSP The contents can be static (HTML Page) or dynamic (Another JSP) The contents of a page can thus be separated into more manageable elements
  • 46. CS3002 Lecture 1 / Slide 46 The include Directive Many dynamic pages contain common static parts in them, mostly header and footer The common static parts can be stored as HTML files that can be included in a JSP Ex: IncludeTestJSP IncludeMeJSP Header.html Footer.html
  • 47. CS3002 Lecture 1 / Slide 47 The taglib Directive The taglib directive will be discussed later in the topic Custom Actions Example: <%@ taglib prefix="blx" uri=“/blx.tld" %> The "uri" specifies where to find the tag library description. The "prefix" is unique for the tag library. This directive is shows that we are using the tags in this library by starting them with blx:
  • 48. CS3002 Lecture 1 / Slide 48 Action tags ACTION TAGS are three types FORWARD ACTION INCLUDE ACTION USEBEAN ACTION
  • 49. CS3002 Lecture 1 / Slide 49 Action Elements Action elements are tags that affect the runtime behavior of a JSP Action elements are also known as Standard Actions Some common standard actions are <jsp:forward> <jsp:include> <jsp:useBean> <jsp:setProperty> <jsp:getProperty> <jsp:param>
  • 50. CS3002 Lecture 1 / Slide 50 Standard Actions - jsp:forward The <jsp:forward> tag is used to forward a request to another page The control will be given to the target page The syntax of the tag is as follows Static url or computed at request time. <jsp:forward page = “Relative url” /> <jsp:forward page = “<%=java expression %>” /> We can pass parameters to the forwarded page using <jsp:param> tag The syntax of using the jsp:param tag is as follows <jsp:forward page = “url”> <jsp:param name = “name” value = “value” /> </jsp:forward>
  • 51. CS3002 Lecture 1 / Slide 51 Standard Actions - jsp:forward Ex: BusinessLogicJSPForm.html BusinessLogicJSP PresentationJSP
  • 52. CS3002 Lecture 1 / Slide 52 Standard Actions - jsp:include The <jsp:include> tag is used to include the contents of another file in a JSP The syntax of the tag is as follows <jsp:include page = “Relative url” /> Unlike the include page directive that pastes the contents of the included file as a part of the JSP, the <jsp:include> tag acts at run time i.e., This action inserts the file at the time the page is requested but not at the time the JSP page is translated into a servlet as like Action Directives If the included file is modified, the next request will receive the modified content in the case of <jsp:include> EX: MyCompanyHome, StockPrice
  • 53. CS3002 Lecture 1 / Slide 53 why java beans in jsp A JavaBean can be defined as a reusable software component write a JavaBean that can then be used in a variety of other Java based softwares such as applications, Servlets or JSP pages. we can define our business logic within a JavaBean and then consistently use that logic in seperate applications. 3 ways of writing code to be used by a JSP. These are, 1. Place the code at the start of a JSP in a declaration, 2. Use an include statement to reference another file which contains the code and now 3. Package the code in a JavaBean (JavaBeans you can fully separate the business logic from the generation of the display.)
  • 54. CS3002 Lecture 1 / Slide 54 Standard Actions - jsp:useBean, jsp:setProperty, jsp:getProperty Minimizing Java code in a JSP will enable even a web designer to maintain it To separate presentation from code, we can encapsulate the logic in a JavaBean JSP can instantiate a JavaBean using the <jsp:useBean> tag, set the bean properties using the <jsp:setProperty> tag and get the bean properties using the <jsp:getProperty> tag syntax: <jsp:useBean id="name" class="package.class" /> Attributes: id, class, scope, type, beanName scope: page | request | session | application
  • 55. CS3002 Lecture 1 / Slide 55 Bean Class package hall; public class SimpleBean { private String message = “Hello, Chakradhar"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } }
  • 56. CS3002 Lecture 1 / Slide 56 Bean laws public no-arg constructor public getter and setter methods. “get” and “set” followed by same word. property name is derived by changing first character to lowercase. Setter argument type and getter return type must be identical You have a property because you have getter and setter methods For use with JSPs property type should be String or primitive. If it isn’t you can’t rely on standard actions and you might have to use scripting
  • 57. CS3002 Lecture 1 / Slide 57 UseBean Action <HTML><BODY> <jsp:useBean id="test” class="hall.SimpleBean" /> <jsp:setProperty name="test” property="message“ value="Hello WWW" /> <H1> Message: <jsp:getProperty name="test“ property="message" /> </H1> </BODY></HTML>
  • 58. CS3002 Lecture 1 / Slide 58 The WishBean Ex: WishBean
  • 59. CS3002 Lecture 1 / Slide 59 Standard Actions - jsp:useBean The <jsp:useBean> tag can be used to create a bean object The important attributes of <jsp:useBean> tag are id class scope The id attribute Specifies the name of the Bean object The class attribute Specifies the fully qualified name of the Bean class
  • 60. CS3002 Lecture 1 / Slide 60 Standard Actions - jsp:useBean The scope attribute Specifies the scope of the Bean object as page, request, session or application The page scope Available only for this request and only in this page By default, the scope will be page The request scope Available only for this request Available to other forwarded and included JSPs The session scope Available to the current session The application scope Available to any JSP in the same application
  • 61. CS3002 Lecture 1 / Slide 61 Standard Actions - jsp:useBean The <jsp:useBean> tag for instantiating the WishBean is as follows <jsp:useBean id = "myWishBean" class = “mypackage.WishBean"/> The above tag is equivalent to the following Java code mypackage.WishBean myWishBean = new mypackage.WishBean();
  • 62. CS3002 Lecture 1 / Slide 62 jsp:setProperty It is used to sets values to properties of beans in two ways 1. use it after, but outside of a jsp:useBean element, which is executed regardless of whether a new bean was instantiated or an existing bean was found. <jsp:useBean id="myName" .../ >... <jsp:setProperty name="myName” property=“anyProperty”… /> 2. appears inside the body of a jsp:useBean element, which is executed only if a new object was instantiated, not if an existing one was found. <jsp:useBean id="myName" ... > ... <jsp:setProperty name="myName” property=“anyProperty”… /> </jsp:useBean>
  • 63. CS3002 Lecture 1 / Slide 63 Standard Actions - jsp:setProperty The <jsp:setProperty> tag can be used to set the Bean properties The attributes are name property param value The name attribute Specifies the id of the Bean object
  • 64. CS3002 Lecture 1 / Slide 64 Standard Actions - jsp:setProperty The property attribute Specifies the name of the bean property that is to be set If this attribute is *, all the request parameters will be assigned to bean properties based on matching name If the request parameter is having a value “”, the bean property is left unaltered The param attribute Specifies the name of the request parameter whose value is to be put in to the bean property If this value is not specified, the value of the request parameter whose name is same as that of the bean property will be assigned to the bean property
  • 65. CS3002 Lecture 1 / Slide 65 <jsp:setProperty> <jsp:useBean … > <jsp:setProperty name=”person” property=”name” param=”username” /> </jsp:useBean> <input type=”text” name=”name”> <jsp:useBean … > <jsp:setProperty name=”person” property=”name” /> </jsp:useBean> If ALL the request parameter names match with the bean property names then <jsp:useBean … > <jsp:setProperty name=”person” property=”*” /> </jsp:useBean>
  • 66. CS3002 Lecture 1 / Slide 66 Standard Actions - jsp:setProperty The value attribute Specifies the value to be assigned to the bean property <jsp:setProperty name=“myWishBean” property=“wish” value=“Welcome” /> The above tag is equivalent to the following Java code myWishBean.setWish(“Welcome”); A tag cannot have both param and value attributes together The <jsp:setProperty tag to set the bean property wish of WishBean to the value Welcome is as follows
  • 67. CS3002 Lecture 1 / Slide 67 <jsp:setProperty> String to primitive doesn’t work with following <jsp:setProperty name=”person” property=”empID” value=”<%=request.getParameter(“empID”)%>” /> But works with <jsp:setProperty name=”person” property=”*” /> <jsp:setProperty name=”person” property=”empID” /> <jsp:setProperty name=”person” property=”empID” value=”343” /> <jsp:setProperty name=”person” property=”empID” param=”empID” />
  • 68. CS3002 Lecture 1 / Slide 68 jsp:getProperty This element retrieves the value of a bean property, converts it to a string, and inserts it into the output. The two required attributes are name of a bean, and property whose value should be inserted. <jsp:useBean id="itemBean" ... />... <UL> <LI>Number of items: <jsp:getProperty name="itemBean" property="numItems" /> <LI>Cost of each: <jsp:getProperty name="itemBean" property="unitCost" /> </UL>
  • 69. CS3002 Lecture 1 / Slide 69 Standard Actions - jsp:getProperty The <jsp:getProperty> tag can be used to get the value of a bean property The attributes are name property The name attribute Specifies the id of the Bean object The property attribute Specifies the name of the bean property to get
  • 70. CS3002 Lecture 1 / Slide 70 Standard Actions - jsp:getProperty The <jsp:getProperty> can be used to get the property wish of the WishBean as follows <jsp:getProperty name = "myWishBean" property = "wish" /> The above tag is equivalent to the following Java code myWishBean.getWish();
  • 71. CS3002 Lecture 1 / Slide 71 Standard Actions - jsp:useBean, jsp:setProperty, jsp:getProperty Ex: BeanTagTestJSP
  • 72. CS3002 Lecture 1 / Slide 72 Standard Actions - jsp:useBean, jsp:setProperty, jsp:getProperty Ex: Employee EmployeeBeanTestJSPForm.html EmployeeBeanTestJSP
  • 73. CS3002 Lecture 1 / Slide 73 Setting attributes at various scopes Servlet JSP Application getServletContext(). application.setAttribute(“foo”,barObj); setAttribute(“foo”,barObj); Request request.setAttribute(“foo”,barObj); request.setAttribute(“foo”,barObj); Session request.getSession(). session.setAttribute( “foo”,barObj); setAttribute(“foo”,barObj); Page Does not apply pageContext.setAttribute(“foo”,barObj); PageContext extends JspContext APPLICATION_SCOPE //static final fields PAGE_SCOPE REQUEST_SCOPE SESSION_SCOPE Methods of JspContext getAttribute(String name, int scope) setAttribute(String name,Object obj,int scope)
  • 74. CS3002 Lecture 1 / Slide 74 Custom Actions In JSP, the programmer can create her own customized tags to encapsulate code from presentation These tags are categorized as Custom Actions The syntax of using custom actions is as follows <prefix:name /> Each custom tag will have an implementation class where the actual Java code resides When the JSP Container comes across a custom tag, the code in the implementation class is executed However, the code will be hidden from the JSP page
  • 75. CS3002 Lecture 1 / Slide 75 The Tag interface The implementation class of a custom tag should implement javax.servlet.jsp.jspext.Tag interface Two important methods of the Tag interface are as follows public int doStartTag() throws javax.servlet.jsp.JspException public int doEndTag() throws javax.servlet.jsp.JspException public int doAfterBody() throws javax.servelt.jsp.JspException These methods are automatically executed when the JSP encounters the starting tag and ending tag of the custom tag
  • 76. CS3002 Lecture 1 / Slide 76 Tag handler execution
  • 77. CS3002 Lecture 1 / Slide 77 The Tag interface The Tag interface has the following final static int fields EVAL_BODY_INCLUDE SKIP_BODY EVAL_PAGE SKIP_PAGE EVAL_BODY_AGAIN The doStartTag() method can return – EVAL_BODY_INLCUDE so that JSP continues evaluating the body of the tag – SKIP_BODY so that JSP skips evaluating the body of the tag The doEndTag() method can return – EVAL_PAGE so that JSP continues evaluating the rest of the page – SKIP_PAGE so that JSP skips evaluating the rest of the page The doAfterBody() method can return – EVAL_BODY_AGAIN so that JSP continues evaluating the body of the tag – SKIP_BODY so that JSP skips evaluating the body of the tag
  • 78. CS3002 Lecture 1 / Slide 78 The TagSupport class The TagSupport class implements the Tag interface and provides blank implementation for all the methods It is easy to extend TagSupport than to implement Tag The doStartTag(), doAfterBody() and doEndTag() methods of TagSupport class return SKIP_BODY, SKIP_BODY and EVAL_PAGE respectively.
  • 79. CS3002 Lecture 1 / Slide 79 The PageContext class A protected object of type javax.servlet.jsp.PageContext called pageContext is declared in the TagSupport class This object can be used to get many attributes of the page like the out, response, request and session objects Eg: JspWriter out= pageContext.getOut(); Some important methods of the PageContext class is as follows public abstract JspWriter getOut() public abstract ServletRequest getRequest() public abstract ServletResponse getResponse() public abstract HttpSession getSession()
  • 80. CS3002 Lecture 1 / Slide 80 Tag handler class .tld file public class SimpleTagTest1 extends <taglib > TagSupport { <tlib-version>1.2</tlib-version> private List movieList; <uri>simpleTags</uri> public void setMovieList(List <tag> movieList) { <description> simple </description> this.movieList=movieList; <name>simple1</name> } <tag-class>foo.SimpleTagTest1</tag-class> public void doStartTag throws <body-content>empty</body-content> JSPException{ <attribute> try { <name>movieList</name> Iterator i= movieList.iterator(); <required>true</required> for … <rtexprvalue>true</rtexprvalue> } catch(IOException e) { </attribute> throw new JspException(“IO”+e.toString()); </tag> } }}
  • 81. CS3002 Lecture 1 / Slide 81 The helloworld Custom Tag Ex: HelloWorld
  • 82. CS3002 Lecture 1 / Slide 82 The taglib Directive Tag Library Descriptor or TLD is an xml file that describes a custom tag Ex: HelloWorldTag.tld The taglib directive is used to tell the JSP the location of TLD <%@ taglib uri=“HelloWorldTag.tld" prefix="tagexample" %> tagdir=“/WEB- <%@ taglib tagdir=“/WEB-INF/tlds/HelloWorldTag.tld" prefix="tagexample" %> used in a JSP as follows The custom tag can be <tagexample:helloworld />
  • 83. CS3002 Lecture 1 / Slide 83 The helloworld Custom Tag Ex: HelloWorldTagTestJSP
  • 84. CS3002 Lecture 1 / Slide 84 The emplist Custom Tag Ex: EmpList EmpListTag.tld EmpListTagLibTestJSP
  • 85. CS3002 Lecture 1 / Slide 85 The hellouser Custom Tag Custom Tags can accept attributes and behave according to their value The TLD file should contain the information about these attributes Ex: HelloUser HelloUserTag.tld HelloUserTagLibTestJSP
  • 86. CS3002 Lecture 1 / Slide 86 Expression Language EL makes nested properties easy to print. JSP supports Expression Language to create a “scriptless” JSP ${param.name} Expression Language or EL provides simpler syntax and implicit objects to perform some of the actions that could be performed by scriptlets – The above EL expression is equivalent to the following scriptlet request.getParameter(“name”)
  • 87. CS3002 Lecture 1 / Slide 87 EL implicit objects pageScope //map of scope attirbutes requestScope sessionScope applicationScope param // map of request parameters paramValues header //map of request headers headerValues cookie initParam //map of context init parameters, not servlet initParameters pageContext //bean
  • 88. CS3002 Lecture 1 / Slide 88 EL ${person.name} same as ${person[“name”] } Person can be bean or map. Name is property or key If person is array or list, above doesn’t work String[] favMusic= {“zero 7”,”tah 80”,” frou frou” }; request.setAttribute(“musicList”, favMusic); If musicList refers to an array. First song: ${musicList[0]} // ${musicList.0} doesn’t work Second song : ${musicList[“1”]} ${param.name} ${paramValues.name[0]} ${request.method} //doesn’t works ${requestScope.method} //works <content-param><param-name>..</..> <param-value> </..> </context-param> ${initParam.email} EL functions: ${param:fun()}
  • 89. CS3002 Lecture 1 / Slide 89 JSP Standard Tag Library - JSTL Many developers creating tag libraries were duplicating many actions as these libraries were created separately There was a need for standardizing the tag libraries, and JSP Standard Tag Library (JSTL) was created based on this JSTL provides a rich set of tags that helps the web designers to perform various actions like iterate over each item in a Collection format process xml access database Application programmers rarely create custom tags and instead use the powerful JSTL and other open source tag libraries
  • 90. CS3002 Lecture 1 / Slide 90 <%@ taglib prefix=“c” uri=“http://java.sun.com/jstl/core”%> <c:set var=“a” value=“sam” /> <c:out value=“${a}” /> String s=request.getParameter(“text1”); same as <c:set var=“s” value=“${param.text1}” >
  • 91. CS3002 Lecture 1 / Slide 91 JSTL tags Some absolute URIs are given for the JSTL library are as follows: For core: http://java.sun.com/jsp/jstl/core For XML: http://java.sun.com/jsp/jstl/xml For Internationalization(date format & currency format): http://java.sun.com/jsp/jstl/fmt For SQL: http://java.sun.com/jsp/jstl/sql For Functions: http://java.sun.com/jsp/jstl/functions core <c: /> xml <xml: /> sql <sql: /> formatting <fmt: /> functions <fn: />
  • 92. CS3002 Lecture 1 / Slide 92 Core tags <c:set <c:out <c:if <c:choose, <c:when , <c:otherwise <c:foreach <c:forTokens <c:import <c:url <c:redirect <c:param
  • 93. CS3002 Lecture 1 / Slide 93 <c:if> <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <html><body> <form method=post action=demo3.jsp> <select name="combo1"> <option value="sam">sam <option value="tom">tom </select> <input type=submit> </form> <c:set var="s" value="${param.combo1}" /> <c:out value="${s}" /> <br> <c:if test="${s eq 'sam' }" > <c:out value="Good Morning...SAM!" /> </c:if> <c:if test="${s = = 'tom'}" > <c:out value=" How Are You?....TOM!" /> </c:if> </body> </html>
  • 94. CS3002 Lecture 1 / Slide 94 <c:choose., <c:when> , <c:otherwise> <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <html> <body bgcolor=lightblue> <form method=post action="demo3.jsp"> <select name="combo1"> <option value="1">1 </option> <option value="2">2 </option> <option value="3">3 </option> <option value="4">4 </option> <option value="5">5 </option> <option value="7">7 </option> </select> <input type=submit> <c:set var="s" value="${param.combo1}" /> Today is <font size=24 color=red> <c:choose> <c:when test="${s==1}">Sunday </c:when> <c:when test="${s==2}">Monday</c:when> <c:when test="${s==3}">Tuesday</c:when> <c:when test="${s==4}">Wednesday</c:when> <c:when test="${s==5}">Thursday</c:when> <c:otherwise> select between 1 & 5 </c:otherwise> </c:choose> </body> </html>
  • 95. CS3002 Lecture 1 / Slide 95 <c:forEach> <c:forEach> action tag contain the following attribute list: items : the collection of items like String[] var : a symbolic name for the collection begin : the starting index of iteration end : the ending index of iteration step : incremental step varStatus: symbolic name for current status. <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:forEach var="n" begin="3" end="8" > <c:out value="${n}" /> <br> </c:forEach>
  • 96. CS3002 Lecture 1 / Slide 96 <c:import> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:import url="welcome.htm"/> <c:out value="to our web-site!" />
  • 97. CS3002 Lecture 1 / Slide 97 <c:url> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <a href= "<c:url value="http://localhost:8080/welcome.htm/>"> send </a> Url encoding
  • 98. CS3002 Lecture 1 / Slide 98 <c:redirect> <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:redirect url="http://localhost:8080/welcome.htm /> Redirecting to the url <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:redirect url="http://localhost:8080/jstldemos/core/sample.jsp" > <c:param name="name1" value="SAM"/> </c:redirect> passing parameters to sample.jsp sample.jsp <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:out value="${param.name1}"/>
  • 99. CS3002 Lecture 1 / Slide 99 books.xml <?xml version="1.0" ?> <books> <book> <title>cobol</title> <author>roy</author> </book> <book> <title>java</title> <author>herbert</author> </book> <book> <title>xml unleashed</title> <author>morrison</author> </book> </books>
  • 100. CS3002 Lecture 1 / Slide 100 JSTL- XML <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib prefix=“x" >uri="http://java.sun.com/jstl/xml" %> <html> <body> <c:import url="books.xml" var="url" /> <x:parse xml="${url}" var="doc" /> <table border=1> <th> <tr> <td>title</td> <td>author</td> </tr> </th> <x:forEach var="n" select="$doc/books/book"> <tr> <td> <x:out select="$n/title" /></td> <td> <x:out select="$n/author" /></td> </tr> Title Author </x:forEach> Cobol Roy </table> </body> </html> Java Herbert We have given a symbolic name for this file as 'url‘ Xml unleashed morrison The resulting tree is given a symbolic name as 'doc'. Magically, we have parsed a given XML document and extracted information, without any mention about DOM,SAX and such words.
  • 101. CS3002 Lecture 1 / Slide 101 students.xml <?xml version="1.0"?> <students> <student> <name>Thomas</name> <place>Delhi</place> <number>1111</number> <mark>78</mark> </student> <student> <name>David</name> <place>Bombay</place> <number>4444</number> <mark>90</mark> </student> </students>
  • 102. CS3002 Lecture 1 / Slide 102 xsl1.xsl <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html> <body> <table border="2" bgcolor="yellow"> <tr> <th>Name</th> <th>Place</th> <th>Number</th> <th>Mark</th> </tr> <xsl:for-each select="students/student"> <tr> <td><xsl:value-of select="name"/> </td> <td><xsl:value-of select="place"/> </td> <td><xsl:value-of select="number"/> </td> <td><xsl:value-of select="mark"/> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>
  • 103. CS3002 Lecture 1 / Slide 103 Transforming xml to xsl using JSTL <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %> <c:import url="students.xml" var="url" /> <c:import url="xsl1.xsl" var="xsl" /> <x:transform xml="${url}" xslt="${xsl}" />
  • 104. CS3002 Lecture 1 / Slide 104 JSTL sql tags <html> <body> <form method=post action="query.jsp"> <textarea name='area1' rows=10 cols=30> </textarea> <input type=submit> </form> </body> </html>
  • 105. CS3002 Lecture 1 / Slide 105 query.jsp <%@ taglib prefix="c" %>uri="http://java.sun.com/jstl/core" <%@ taglib prefix="sql" %> uri="http://java.sun.com/jstl/sql" <html> <body> <sql:setDataSource var="db" driver="sun.jdbc.odbc.JdbcOdbcDriver" url="jdbc:odbc:dbdemo" /> <c:set var='s' value="${param.area1}" /> <c:out value="${s}" /> <br> <sql:query var="query1" dataSource="${db}" sql="${s}" /> <table border="1"> <c:forEach var="row" items="${query1.rows}" > <tr> <td> <c:out value="${row.name}" /></td> <td> <c:out value="${row.place}" /></td> </tr> </c:forEach> </table> </body> </html>
  • 106. CS3002 Lecture 1 / Slide 106 Function tags <c:out value="${fn:replace(string,find,replaceWith)}"/> <c:out value="${fn:indexOf(text,str)}"/> <c:forEach var="num" items="${fn:split(str1, ' ')}"> <c:out value="${num}" /> </c:forEach> <c:out value="${fn:substring(string,start,end)}"/> <c:out value="${fn:substringBefore(fString,sString)}"/> <c:out value="${fn:substringAfter(fString,sString)}"/> <c:set var="trimText" value="${fn:trim(text)}"/>
  • 107. CS3002 Lecture 1 / Slide 107 <fn:escapeXml(String)> Tag of JSTL <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <html> <head> <title>Example of fn:escapeXml Tag</title> </head> <body> <c:set var="str1" value="This is first String."/> <c:set var="str2" value="This <abc>is second String.</abc>"/> <c:set var="str3" value="<mahendra>This is first String.</mahendra>"/> <h4>fn:escapeXml</h4> <table border="1"> <tr> <th>without fn:escapeXml</th> <th>with fn:escapeXml</th> </tr> <tr> <td>${str1}</td> <td> ${fn:escapeXml(str1)} </td> </tr> <tr> <td>${str2}</td> <td> ${fn:escapeXml(str2)} </td> </tr> <tr> <td>${str3}</td> <td> ${fn:escapeXml(str3)} </td> </tr> </table> </body> </html>
  • 108. CS3002 Lecture 1 / Slide 108 Summary JSP is a technology for coding the presentation logic of an enterprise application Web designers without programming skills can create and maintain JSP The Standard Actions and Custom Actions help to encapsulate the code from presentation Rich, Open Source, Standard Tag Libraries are available
  • 109. CS3002 Lecture 1 / Slide 109 References http://www.roseindia.net/jsp/ http://www.roseindia.net/jstl/jstlxmltags.shtml http://www.roseindia.net/jstl/jstsqlltags.shtml http://www.roseindia.net/jsp/implement-javascript-with-jsp.shtml http://www.roseindia.net/jsp/loginbean.shtml http://www.roseindia.net/jsp/loginstatus.shtml http://www.roseindia.net/jsp/DisplayimageonJSPpageusingXML.shtml http://www.roseindia.net/jsp/ExampleOfPrintingTextMessage.shtml http://www.roseindia.net/jsp/embeddingwmp.shtml http://www.roseindia.net/jsp/core-xml-tag.shtml http://www.roseindia.net/jsp/parsing-xml.shtml http://www.roseindia.net/jsp/applet-jsp.shtml http://www.roseindia.net/jsp/add-flash-jsp.shtml http://www.gulland.com/courses/JavaServerPages/jsp_beans.jsp
  • 110. CS3002 Lecture 1 / Slide 110 Applications http://www.roseindia.net/jsp/bank.shtml http://www.roseindia.net/jsp/online-quiz-application- jsp.shtml http://www.roseindia.net/jsp/paging.shtml http://www.roseindia.net/jsp/file_upload/uploadingMul tipleFiles.shtml http://www.roseindia.net/jsp/jsp-frameset.shtml