Java Server Pages
1. It is a technology for developing portable java web applications
   that runs on a java web server.
2. Main motivation behind developing JSP was to develop a
   technology so that a non-java programmer or a person with little
   knowledge of java could write web applications for java plaform.
3. Initially JSP was developed to replace servlet but now common
   practice is to use servlet and jsp together using MVC(model-
   view-controller) pattern.
4. JSP allows developer to write html (static content),jsp action
   tags and java (dynamic content) code in the same page.
5. JSPs are compiled into java servlets by a jsp compiler, thus
   internally jsp page is converted into servlet, it is must to
   understand java servlet technology throughly for becoming a
   good jsp programmer.
            Java Server Pages
• JSP enables you to separate the dynamic
  content of a web page from its presentation. It
  caters to different types of developers.
• Web designers, are responsible for the
  graphical design of the page
• Java developers, write the code to generate
  dynamic content.
JSP - Architecture
JSP Processing
                  JSP - Life Cycle
• The following are the paths followed by a JSP
   –   Compilation
   –   Initialization
   –   Execution
   –   Cleanup
        Cont..                  JSP Life Cycle
JSP life cycle includes following steps/phases:
•    JSP page translation – generate servlet source code
     The translation occurs only when jsp page has to serve its first
     request. Translation does not have to happen again unless the page
     is updated.
•    JSP page compilation – compile generated code into byte code
•    Load class
•    Create instance
•    Call the jspInit method
•    Call the _jspService method - for each request
•    Call the jspDestroy method
                  JSP API
Translated         JSP        Servlet        implements
  javax.serlvet.jsp.HttpJspPage interface, which is a
  sub interface of javax.servlet.jsp.JspPage.
The javax.servlet.jsp.JspPage interface contains two
  methods:
1. public void jspInit() - This method is invoked
  when the JSP is initialized and the page authors are
  free to provide initialization of the JSP by
  implementing this method in their JSPs.
2. public void jspDestroy() - This method is
  invoked when the JSP is about to be destroyed by
  the container. Similar to above, page authors can
  provide their own implementation.
    Cont…                   JSP API
The javax.servlet.jsp.HttpJspPage interface
 contains one method:
public void _jspService(HttpServletRequest
 request, HttpServletResponse response)
 throws ServletException, IOException
This method generated by the JSP container is
 invoked, every time a request comes to the
 JSP. The request is processed and the JSP
 generates appropriate response. This response
 is taken by the container and passed back to
 the client.
          JSP Elements
A. Directives
B. Scripting Elements
C. JSP Actions
         (B) Scripting Elements
4 types of scripting elements defined:
•   Declaration
•   Expression
•   Scriptlets
•   Comments
               (B-1)Declaration
Declares a variable or method valid in the scripting language
  used in the JSP page.
JSP Syntax
      <%! declaration; [ declaration; ]+ ... %>
Examples
      <%! int i = 0; %>
      <%! int a, b, c; %>
      <%! Circle a = new Circle(2.0); %>
   Cont..          Declaration
• Any number of variables or methods
  can be declared within one declaration
  element, as long as you end each
  declaration with a semicolon.
• We can use declaration to write
  anything that would be placed in the
  generated servlet outside of the
  _jspService method.
      Cont…              JSP Declaration Tag
• A declaration declares one or more variables or methods
  that you can use in Java code later in the JSP file.
Syntax: <%! field or method declaration %> or
         <jsp:declaration> code fragment </jsp:declaration>
<html>     <body>
<%!
int cube(int n){
return n*n*n*;       }                           Welcome.jsp
%>
<%= "Cube of 3 is:"+cube(3) %>
</body> </html>
                 (B-2) Expression
Syntax
<%= expression %>
Description
The code placed within JSP expression tag is written to the output
  stream of the response. So you need not write out.print() to
  write data. It is mainly used to print the values of variable or
  method.
Example
Welcome, <%=userName%>
Output:
Welcome, Jay
       Cont…             Expression
<%= new java.util.Date()%>
When this is generated into servlet code, the resulting
  java stmt will probably look like this:
out.print(new java.util.Date());
<html> <body>
Current Time: <%=
 java.util.Calendar.getInstance().getTime()
 %>
</body>
</html>
            (B-3) Script lets
It is used to execute java source code in JSP.
Syntax : <% java source code %> OR
      <jsp:scriptlet> code fragment
  </jsp:scriptlet>
Scriptlets allows you to include a series of java
  statements inside the _jspService method
  that are executed on every request to the
  page. These java stmts are incorporated into
  _jspService method as it is.
                   JSP scriptlet tag
  • Used to execute java source code in JSP
      – Syntax:      <% java source code %>
Welcome.html:-
<html>
<body>
 <form action="welcome.jsp">
                                 Welcome.jsp:-
<input type="text" name="uname"> <html>
                                    <body>
<input type="submit" value="go">   <%
<br/>                              String
</form> </body>                    name=request.getParameter(“uname
</html>                            ”);
                                   Out.print(“welcome”+name);
                                   %>
                                   </body> </html>
           (B-4) Comments
To denote any lines you want to be completely
 ignored by the JSP translation process.
Example
<%-- Author: James Gosling --%>
          (A) JSP Directives
They are the elements of a JSP source code that
  guide the web container on how to translate
  the JSP page into it’s respective servlet.
  Syntax:
<%@ directive attribute = "value"%>
There are three main directives defined in jsp:
• Page
• Include
• Taglib
          (A-1) Page Directive
It is used to define the properties applying the JSP page,
   such as the size of the allocated buffer, imported
   packages and classes/interfaces, defining what type of
   page it is etc.
Syntax
   <%@page attribute = "value"%>
               OR
   <jsp:directive.page pageDirectiveAttrList />
Examples
 <%@ page import="java.util.*, java.lang.*" %>
 <jsp:directive.page errorPage="error.jsp" />
     Cont..            Page Directive
Description
• It applies to an entire JSP page and any of its
  static include files, which together are called a
  translation unit.
• The page directive does not apply to any
  dynamic resources;
• You can use the page directive more than
  once in a translation unit, but you can only
  use each attribute, except import, once.
Cont.. Different Attributes of JSP page directive
  o    import
  o    contentType
  o    extends
  o    info
  o    buffer
  o    language
  o    isELIgnored
  o    isThreadSafe
  o    autoFlush
  o    session
  o    pageEncoding
  o    errorPage
  o    isErrorPage
                       See the reffered file detail(with examples)
            (A-2) Include Directive
Used to include the contents of any resource, it may be jsp file, html
  file or text file. The include directive includes the original content of
  the included resource at page translation time (the jsp page is
  translated only once so it will be better to include static resource).
Advantage: Code Reusability
Syntax: <%@ include file="resourceName" %> OR
  <jsp:directive.include file=" resourceName " />
Examples:include.jsp:
<html> <head>
<title>An Include Test</title> </head>
<body bgcolor="white">
<font color="blue">
The current date and time are <%@ include file="date.jsp" %>
</font> </body> </html>
             Cont… Include Directive
date.jsp
 <%@ page import="java.util.*" %>
<%= (new java.util.Date() ).toLocaleString() %>
Description
An include directive inserts a file of text or code in a JSP page at
  translation time, when the JSP page is compiled. When you use the
  include directive, the include process is static. A static include
  means that the text of the included file is added to the JSP page. The
  included file can be a JSP page, HTML file, XML document, or text
  file. If the included file is a JSP page, its JSP elements are translated
  and included (along with any other text) in the JSP page. Once the
  included file is translated and included, the translation process
  resumes with the next line of the including JSP page.
             (A-3) taglib directive
Used to mention the library whose custom-defined tags are being used
  in the JSP page. It’s major application is JSTL(JSP standard tag
  library).
Syntax:
<%@taglib uri = "library url" prefix="the prefix to identify the tags of this library
  with"%>
Examples
<%@ taglib uri="http://www.jspcentral.com/tags" prefix=“abc" %>
<abc:loop> ... </abc:loop>
Description
• The taglib directive declares that the JSP page uses custom tags, names
  the tag library that defines them, and specifies their tag prefix.
• You must use a taglib directive before you use the custom tag in a JSP
  page. You can use more than one taglib directive in a JSP page, but the
  prefix defined in each must be unique.
               (C) JSP ACTIONS
The JSP specification provides a standard tag called Action tag used
  within JSP code and is used to remove or eliminate Scriptlet code
  from your JSP code as JSP Scriptlets are obsolete and are not
  considered nowadays. There are many JSP action tags or elements,
  and each of them has its own uses and characteristics. Each JSP
  action tag is implemented to perform some precise tasks.
Here is the list of JSP Actions:
                             jsp:forward
  The jsp:forward tag is used to forward the request and response to
  another JSP or servlet. In this case the request never return to the
  calling JSP page. (internally uses RequestDispatcher forward()
  method)
jsp:param/                         jsp:params
   The jsp:param action is used to add the specific parameter to
   current request. The jsp:param tag can be used inside a jsp:include,
   jsp:forward or jsp:params block.
       Cont..         JSP ACTIONS
                      jsp:include
Work as a subroutine, the Java servlet temporarily passes
the request and response to the specified JSP/Servlet.
Control is then returned back to the current JSP page.
                      jsp:useBean
Used to instantiate an object of Java Bean or it can re-use
existing java bean object.
                   jsp:getProperty
Used to get specified property from the JavaBean object.
                   jsp:setProperty
Used to set a property in the JavaBean object.
                      jsp:forward
• The <jsp:forward> element forwards the request object containing the
  client request information from one JSP page to another resource.
• The target resource can be an HTML file, another JSP page, or a
  servlet, as long as it is in the same application context as the forwarding
  JSP page. The lines in the source JSP page after the <jsp:forward>
  element are not processed.
Attributes
page="{relativeURL | <%= expression %>}"
   – A String or an expression representing the relative URL of the
      component to which you are forwarding the request. The component
      can be another JSP page, a servlet, or any other object that can
      respond to a request.
   – The relative URL looks like a path--it cannot contain a protocol
     name, port number, or domain name. The URL can be absolute or
     relative to the current JSP page. If it is absolute (beginning with a /),
     the path is resolved by your web or application server.
                jsp:forward
Forwards a request to a web resource.
JSP Syntax
<jsp:forward page="{relativeURL | <%= expression %>}" />
                    or
<jsp:forward page="{relativeURL | <%= expression %>}"
  >
<jsp:param
  name="parameterName"         value="{parameterValue |
  <%= expression %>}" />
</jsp:forward>
Examples
<jsp:forward page="/servlet/login" />
<jsp:forward page="/servlet/login">
   <jsp:param name="username" value="jsmith" />
</jsp:forward>
                 jsp:include
Includes a static file or the result from another web
  component.
JSP Syntax
<jsp:include page="{relativeURL | <%= expression
  %>}" />
            or
<jsp:include page="{relativeURL | <%= expression
  %>}" />
   <jsp:param
  name="parameterName"             value="{parameter
  Value | <%= expression %>}" />
 </jsp:include>
          jsp:useBean
The <jsp:useBean> element locates
  or instantiates a JavaBeans
  component. It first attempts to
  locate an instance of the bean. If
  the bean does not exist,
  <jsp:useBean> instantiates it
  from a class or serialized
  template.
                jsp:useBean
Examples
<jsp:useBean id="cart" scope="session"
  class="session.Carts" />
<jsp:setProperty name="cart" property="*" />
<jsp:useBean id="checking" scope="session"
  class="bank.Checking" >
   <jsp:setProperty name="checking"
  property="balance" value="0.0" />
</jsp:useBean>
               jsp:useBean
• class="package.class" type="package.class"
   – Instantiates a bean from the class named in
     class and assigns the bean the data type you
     specify in type. The value of type can be the
     same as class, a superclass of class, or an
     interface implemented by class.
   – The class you specify in class must not be
     abstract and must have a public, no-argument
     constructor. The package and class names you
     use with both class and type are case sensitive.
        jsp:useBean Example
<html><body>
<form method=‘post’ action=‘usebeanexample.jsp’>
Name:<input type=‘text’ name=‘name’/><br>
Branch:<input type=‘text’ name=‘address’/><br>
RollNo:<input type=‘text’ name=‘rollNo’/><br>
Date of Birth:<input type=‘text’ name=‘dob’/><br>
<input type=‘submit’/><input type=‘reset’/>
</form>
</body></html>
Cont…           jsp:useBean Example
public class Student{
       String name,address,rollNo,dob;
       public Student(){}
       String getName(){ return name;}
       String setName(String name){this.name=name;}
       String geAddress(){ return address;}
       String setAddress(String
  address){this.address=address;}
       String getRollNo(){ return rollNo;}
       String setRollNo(String rollNo){this.rollNo=rollNo;}
       String getDOB(){ return dob;}
       String setDOB(String dob){this.dob=dob;}
       }
  Cont…             jsp:usebean Example
Usebeanexample.jsp
<%@page language=‘java’ %>
<jsp:useBean id=‘stuobj’ class=“Student” scope=‘request’>
       <jsp:setProperty name=‘stuobj’ property=‘name’/>
       <jsp:setProperty name=‘stuobj’ property=‘address’/>
       <jsp:setProperty name=‘stuobj’ property=‘rollNo’
  param=‘rollNo’/>
       <jsp:setProperty name=‘stuobj’ property=‘DOB’
  param=‘dob’/>
</jsp:useBean>
<% out.print(“student name is”+stuobj.getName());
       %>
              JSP Implicit Objects
• There are 9 jsp implicit objects. These objects
  are created by the web container that are available to all
  the jsp pages.
  Object                       Type
   out                          JspWriter
   request                      HttpServletRequest
   response                     HttpServletResponse
   config                       ServletConfig
   application                  ServletContext
   session                      HttpSession
   pageContext                  PageContext
   page                         Object
   exception                    Throwable
          1) JSP out implicit object
     • To write data on output stream
Prog 1: Welcome.jsp:-          Prog 2: ShowDate.jsp:-
<html>                         <html>      <body>
<body>                         <% out.print("Today
<%
                               is:"+java.util.Calendar.getI
Out.print(“welcome to JSP”);
%>
                               nstance().getTime()); %>
</body>                        </body>
</html>                        </html>
            2- JSP request object
• It can be used to get request information such as parameter, header
  information, remote address, server name, server port, content type,
  character encoding etc.
• It can also be used to set, get and remove attributes from the jsp
  request scope.                 Welcome.jsp:-
                                 <html>
Welcome.html:-
                                  <body>
<html>
                                 <%
<body>
 <form action="welcome.jsp">     String
<input type="text" name="uname"> name=request.getParameter(“uname”);
                                 Out.print(“welcome”+name);
<input type="submit" value="go"> %>
<br/>
</form>                          </body>    </html>
</body> </html>
           3- The response Object:
• It can be used to add or manipulate response such
  as redirect response to another resource, send error
  etc.                        Welcome.jsp:-
Welcome.html:-                   <html>
<html>                            <body>
<body>                           <%
 <form action="welcome.jsp">     response.sendRedirect(“http:
<input type="text" name="uname">
                                   //google.com”)
<input type="submit" value="go">   %>
<br/>
</form>                            </body>
</body>                            </html>
</html>
         4- Application Object
• Any attribute set by application implicit
  object would be available to all the JSP
  pages.
• It is different from session
• It’s mostly used methods are:-
    • Integer                   counter                    =
      (Integer)application.getAttribute(“Visit");
    • application.setAttribute(“Visit”,             counter);
Example:
    <%@ page import="java.io.*,java.util.*" %>
    <html> <head> <title>Application Implicit Object Example</title>
    </head>        <body>
     <%
    Integer counter= (Integer)application.getAttribute("numberOfVisits");
    if( counter ==null || counter == 0 )
    {
    counter = 1;
    }
    else           {
    counter = counter+ 1;
    }
    application.setAttribute("numberOfVisits", counter);
    %>
    <h3>Total number of hits to this Page is: <%= counter%></h3>
    </body>        </html>
                     5- Session Object
Welcome.html:-                         Welcome.jsp:-
<html>                                 <html>
<body>                                  <body>
 <form action="welcome.jsp">           <%
<input type="text" name="uname">       String
    • type="submit" value="go">
<input                                 name=request.getParameter(“uname”);
<br/>                                  session.setAttribute("user“, name); %>
</form>                                <a href=“second.jsp”>second page</a>
</body>                                </body>
</html>                                 </html>
      Second.jsp:-
      <html>
      <body>
      <%
      String name=(String)session.getAttribute("user");
      out.print("Hello "+name);
      %>
      </body>
      </html>