JSP Basics (Part-I)

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

  1. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
    http://www.techgeek.in

    Introduction



    A JavaServer Page (JSP) is a template for a web page that uses Java code to generate an HTML document dynamically.They are run on the server in a JSP container which translates them into equivalent servlets.They are text files similar to HTML pages with some additional tags which generate dynamic content.Servlets and JSP pages are intimately related.JSP has the following advantages over servlets:

    • They are automatically recomplied when necessary.
    • They are HTML like so they have greater compatibility with web development tools.
    • Addressing JSP pages is simpler than addressing servlets.

    Process Of Execution Of A Request



    The following steps execute a JSP request from the time the request is received from client until it is processed and sent back to client.

    Step1:- Request from Client: A JSP page has the extension as .jsp. The client request is made on the web browser by going to the .jsp extension JSP file.

    Step2:-Request Sent To Server: The request received from client (web browser) is sent to the server side.

    Step3:-JSP Servlet Engine: Since the extension of request made has .jsp extension, it indicates that it is a JSP file and therefore the web server passes the request received to the JSP Servlet Engine.

    Step4:-Process of generating servlet: JSP files are compiled by the JSP engine into a servlet. This step creates the .jsp file as a Java servlet source file.

    Step5:-Process of making class file:
    The source file from Step4 is compiled into a class file.

    Step6:- Instantiation of Servlet: The instantiation of servlet is performed using the init and service methods. In these methods, the jspInit() method is defined by the developer and the jspService method is generated by the JSP engine.

    Step7:-Output HTML: `The request received from client is executed and the output is sent as HTML.

    Step8:- Client Receives the Output: The Client Receives the Output and thus the result namely the HTML gets displays in the client browser.

    Life Cycle Of A JSP



    Translation:-The first stage in the life cycle of a JSP is known as the translation phase.When a request is first made for a JSP (assuming it hasn’t been precompiled), the JSP engine will examine the JSP file to check that it’s correctly formed and the JSP syntax is correct. If the syntax check is successful then the JSP engine will translate the JSP into its page implementation class, which takes the form of a standard Java servlet. Once the page’s implementation servlet has been created it will be compiled into a class file by the JSP engine and will be ready for use. Each time a container receives a request, it first checks to see if the JSP file has changed since it was last translated. If it has, it’s retranslated so that the response is always generated by the most up-to-date implementation of the JSP file.

    Initialization:-Once the translation phase has been completed, the JSP engine will need to load the generated class file and create an instance of the servlet in order to continue processing of the initial request. Therefore, the JSP engine works very closely with the servlet container and the JSP page implementation servlet and will typically load a single instance of the servlet into memory. As you may or may not be aware, the Java Servlet Specification provides two separate threading models that can be used. The models determine whether single or multiple instances of a servlet can exist. As with servlets, the default threading model is the multithreaded one that requires no additional work for the developer. To select the single-threaded model for your JSP, there’s an attribute of the page directive called isThreadSafe that must be set to false to serialize all requests to the implementation servlet behind the JSP:

    <%@ page isThreadSafe="true" %>

    Of course such directives must be placed in the JSP so that the JSP engine can make the necessary changes to the page implementation servlet during the translation phase.

    Servicing:- Once the JSP and servlet containers have completed all of their preliminary work, the initial request can be serviced. There are three important methods that are generated in the page implementation servlet by the JSP engine during the translation phase. These three methods bear a striking resemblance to the init(), service(), and destroy() methods from the javax.servlet.Servlet interface. They’re the key methods involved in the life cycle of a servlet.

    jspInit()

    As the name suggests, this method is used for initializing the implementation servlet in an identical manner to the standard servlet init() method, which is used to initialize a servlet. The behavior of both methods can be regarded as identical and each is called exactly once.

    Although this method is automatically generated during the translation phase, it’s possible to override this method in the JSP using a declaration. It can be used for initializing the JSP in order to open a database connection or initialize some session and context variables, for example.

    <%! Connection conn = null; %>
    <%!
    public void jspInit() {
    try {
    conn = getConnection(…);
    } catch (SQLException sqle){}
    }
    %>

    _jspService()

    This method provides all of the functionality for handling a request and returning a response to the client. All of the scriptlets and expressions end up inside this method, in the order in which they were declared inside the JSP. Notice that JSP declarations and directives aren’t included inside this method because they apply to the entire page, not just to a single request, and therefore exist outside the method. _jspService() may not be overridden in the JSP.

    Destruction:- The final method worthy of explanation that is generated as a result of the translation phase is the jspDestroy() method. Like the destroy() method found in a normal servlet, this method is called by the servlet container when the page implementation servlet is about to be destroyed. This destruction could be for various reasons, such as the server being low on memory and wanting to free up some resources, but the most common reason would be when the servlet container is shutting down or being restarted.

    Once this method has been called, the servlet can no longer serve any requests. Like the destroy() method, jspDestroy() is an excellent place to release or close resources such as database connections when the servlet is shutting down. To do this, simply provide an implementation of this method via a JSP method declaration. For example, to close the database connection you opened inside the jspInit() method, you would use the following:

    <%!
    public void jspDestroy() {
    try {
    conn.close();
    } catch (SQLException sqle){}
    conn = null;
    }
    %>

    This is a simple JSP page that displays the current date:-


    Code:
    <html>
    	<head>
    		<title>Date</title>
    	</head>
    	<body>
    		<h3>
    			The date is
    			<% out.println((new java.util.Date()).toString()); %>
    		</h3>
    	</body>
    </html>
    
    Write this code in notepad and save it as date.jsp. Keep this file in the webapps/jsp folder.

    Start Tomcat and go to http://localhost:8080/jsp/date.jsp

    A lot of things happen behind the scenes when a JSP page is deployed in a web container and is first served to a client request. As mentioned before in the life cycle Deploying and serving a JSP page involves two distinct phases:

    • Translation phase - In this phase the JSP page is transformed into a Java servlet and then compiled. This phase occurs only once for each JSP page and must be executed before the JSP page is served. The generated servlet class is known as a JSP page implementation class.
    • Execution phase - This phase (also known as the request processing phase), is executed each time the JSP page is served by the web container to a client. Requests for the JSP page by a client results in the execution of the JSP page implementation class.

    The class implements javax.servlet.jsp.HttpJspPage or javax.servlet.jsp.JspPage, both of which extend javax.servlet.Servlet. The following code is the source for the page implementation class of date.jsp.

    The class extends HttpJspBase, which is a class provided by Tomcat that implements the HttpJspPage interface.

    Code:
        package org.apache.jsp;
        import javax.servlet.*;
        import javax.servlet.http.*;
        import javax.servlet.jsp.*;
        import org.apache.jasper.runtime.*;
        public class date$jsp extends HttpJspBase {
         
          public date$jsp() {}
    
          private static boolean _jspx_inited = false;
    
    /*When a request comes for the JSP page, the container creates an instance of the page and calls the jspInit() method on the page implementation object. */
    
          public final void _jspx_init()
            throws org.apache.jasper.runtime.JspException {}
    
    /*
    The generated class overrides the _JSP pageservice() method. This method is called each time the JSP is accessed by a client browser. All the Java code and template text we have in our JSP pages normally go into this method. 
    */
    
    
          public void _JSP pageservice(HttpServletRequest request,
                                  HttpServletResponse response)
              throws java.io.IOException, ServletException {
    
            JspFactory _jspxFactory = null;
            PageContext pageContext = null;
            HttpSession session = null;
            ServletContext application = null;
            ServletConfig config = null;
            JspWriter out = null;
            Object page = this;
            String _value = null;
    
            try {
              if (_jspx_inited == false) {
                synchronized (this) {
                  if (_jspx_inited == false) {
                      _jspx_init();
                      _jspx_inited = true;
                }
            }
          }
          _jspxFactory = JspFactory.getDefaultFactory();
          response.setContentType("text/html;charset=ISO-8859-1");
          pageContext = _jspxFactory.getPageContext(this, request, response,
                                                    "", true, 8192, true);
    
    
    //Here we initialize the implicit variables:
    
    
             application = pageContext.getServletContext();
             config = pageContext.getServletConfig();
             session = pageContext.getSession();
             out = pageContext.getOut();
             out.write("<html>\r\n<head>\r\n<title>Date</title>\r\n" +
                        "</head>\r\n<body>\r\n<h3>\r\n" + "The date is\r\n");
               out.println((new java.util.Date()).toString());
              out.write("\r\n    </h3>\r\n </body>\r\n</html>");
              
       } catch (Throwable t) {
                if (out != null && out.getBufferSize() != 0) {
                  out.clearBuffer();
                }
                if (pageContext != null) {
                  pageContext.handlePageException(t);
                }
              } finally {
                 if (_jspxFactory != null) {
                   _jspxFactory.releasePageContext(pageContext);
                 }
              }
            }
         }
    


    List Of Tags Used In Java Server Pages




    Declarations



    Declarations are used to define class wide variables and methods in the generated servlet. They are initialized when the JSP page is initialized and have instance scope in the generated servlet so that anything in a declaration is available throughout the JSP to other declarations, expressions and code. They do not produce any output that is sent back to the client.

    Declarations in JSP pages are embedded between <%! and %> delimiters and its general syntax is

    <%! Java variable and method declarations %>

    for example:

    ShowTimeD.jsp

    Code:
    <%@ page import=”java.text.*,java.util.*” %>
    <%!
        DateFormat fmt=new SimpleDateFormat(“hh:mm:ss aa”);
        String now=fmt.format(new Date());
    %>
    <html>
    <head>
    <title>Declaration test page</title>
    <body>
    	<h1> Declaration test page </h1>
    	<p> The time is <%= now %></p>
    </body>
    </html>
    
    Write this code in notepad and save it ShowTimeD.jsp. Keep this file in the webapps/jsp folder.

    Start Tomcat and go to http://localhost:8080/jsp/ShowTimeD.jsp

    The time is 10:49:40 PM
    But when the page is refreshed the output remains the same:
    The time is 10:49:40 PM
    The time is 10:49:40 PM
    The time is 10:49:40 PM
    This is because the declaration in the JSP is not placed in the _jspService() method of the generated servlet.They are inserted directly in the class itself to define static or instance variables and methods.

    Another Example:-
    Code:
    <html>
    <body>
    <%! 
         private int example = 0 ; 
         private int test = 5 ; 
    %>
    
    <%@page contentType="text/html" %> 
    
    <%!
    int cnt=0;
    private int getCount(){
    	//increment cnt and return the value
    	cnt++;
    	return cnt;
    }
    %>
    
    	<p>Values of Cnt are:</p>
    
    	<p><%=getCount()%></p>
    
    	<p><%=getCount()%></p>
    
    	<p><%=getCount()%></p>
    
    	<p><%=getCount()%></p>
    
    	<p><%=getCount()%></p>
    
    	<p><%=getCount()%></p>
    
    </body>
    
    </html>
    
    

    Scriptlets



    Scriptlets are blocks of Java code that is executed during request processing time.The contents of scriptlets go within the _JSP pageservice() method. Scriptlets are embedded between <% and %> delimiters and its general syntax is

    <% valid java code statements %>

    for example:
    Code:
        <%
          int x = 10;
          int y = 20;
          int z = 10 * 20;
        %> 
    
    Here is an example of a JSP page that uses a scriptlet to generate a table of ASCII. characters:


    Code:
    <HTML>
    <BODY>
    <CENTER>
    <H3>ASCII Table</H3>
    <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0">
    <%
       StringBuffer sb = new StringBuffer();
       sb.append("<TR>");
       sb.append("<TH WIDTH=40>&nbsp;</TH>");
       for (int col = 0; col < 16; col++) {
          sb.append("<TH>");
          sb.append(Integer.toHexString(col));
          sb.append("</TH>");
       }
       sb.append("</TR>");
       for (int row = 0; row < 16; row++) {
          sb.append("<TR>");
          sb.append("<TH>");
          sb.append(Integer.toHexString(row));
          sb.append("</TH>");
          for (int col = 0; col < 16; col++) {
             char c = (char)(row * 16 + col);
             sb.append("<TD WIDTH=32 ALIGN=CENTER>");
             sb.append(c);
             sb.append("</TD>");
          }
          sb.append("</TR>");
       }
       out.println(sb);
    %>
    </TABLE>
    </CENTER>
    </BODY>
    </HTML>
    
    Write this code in notepad and save it ASCII_Table.jsp. Keep this file in the webapps/jsp folder.
    Start Tomcat and go to http://localhost:8080/jsp/ASCII_Table.jsp
    [​IMG]

    Expressions



    An Expression is a shorthand notation for a scriptlet that sends the value of a java expression back to the client.The expression is evaluated at HTTP request processing time and if the output is a Java primitive, the value of the primitive is printed back to the browser. If the output is a Java object, the result of calling the toString() method on the object is written back to the browser.

    An expression is enclosed in <%= and %> tags and its general syntax is

    <%= Java expression to be evaluated %>

    For example:
    This expression would print the string 10 to the client:

    Code:
        <%= Math.sqrt(100) %> 
    Output:

    10

    Another Example:

    Code:
    <html>
    <head>
    <title>
    Expression test page
    </title>
    </head>
    <body>
    <h1> Expression test page
    </h1>
    <%! int i=0; %>
    <% i++; %>
    HELLO WORLD!!
    <%= "This JSP has been accessed " + i + "times" %>
    </body>
    </html>
    
    Write this code in notepad and save it expression.jsp. Keep this file in the webapps/jsp folder.
    An int variable I is declared with an initial value 0. Each time this instance of the generated servlet is called for example when the browser requests http://localhost:8080/jsp/expression.jsp
    The variable I is incremented. Finally the value of i is printed using an expression.

    Start Tomcat and go to http://localhost:8080/jsp/expression.jsp
    The first time the client types the above url i =0.

    [​IMG]

    The next time i is 1.

    [​IMG]

    Directives



    Directives are messages sent by the JSP author to the JSP container to aid the container in the process of page translation. These directives are used by the JSP container to import tag libraries, import required classes, set output buffering options, and include content from external files.
    Directives begin with <%@ and end with %> and the general syntax is:

    <%@ directivename attribute=”value” attribute=”value” %>


    The JSP specification defines three main directives:

    • page - provides general information about the page, such as the scripting language that is used, content type, or buffer size .
    • include - used to include the contents of external files.
    • taglib - used to import custom actions defined in tag libraries.

    The page Directive:- The page directive sets a number of page dependent properties that can be used during the translation phase by the container. A JSP page can contain any number of page directives. However only the import attribute should appear more than once.

    The following table shows the different attributes associated with the page directive:

    Attribute ---------> Description
    1) language -------> Defines the server-side scripting language used in the JSP. The only language that is currently supported is Java.
    2) extends --------> Defines the name of the class the page implementation class should extend. This attribute is generally not used by page authors. It is left to the container to decide the ancestor of the page implementation class.
    3) import ---------> Allows us to import packages and classes to be used within scriptlets. The packages and classes are defined as a comma separated list.
    4) session --------> Defines whether the page should participate in a session. The session implicit variable is available for scripting only if the value of this attribute is set to true. The default value is true.
    5) buffer ---------> Defines the buffer size for the JSP in kilobytes. If set to none, the output of the JSP is not buffered.
    6) autoFlush ------> If set to true the buffer will be flushed when the maximum limit is reached. Otherwise an IllegalStateException is thrown.
    7) isThreadSafe ---> If set to false, the page implementation class will implement the SingleThreadModel interface. The default value is true.
    8) info -----------> The value of this attribute is returned by the getServletInfo() method of the page implementation class.
    9) errorPage ------> Defines the relative URI of the web resource to which the response should be forwarded if an exception is thrown in the JSP page.
    10) contentType ---> Defines the MIME type for the output response. The default value is text/html.
    11) isErrorPage ---> Should be set to true for JSP pages that are defined as error pages.
    12) pageEncoding --> Defines the character encoding for the page.

    The following snippet shows an example of the page directive:
    Code:
        <%@ page language="java" buffer="10Kb" autoFlush="true"
                 errorPage="/error.jsp" import="java.util.*”  %>
    <html>
    <head>
    <title>
    Page Directive Tset Page
    </title>
    </head>
    <body>
    <h1>Page Directive Test Page</h1>
    This is a JSP page to test the page directive
    </body>
    </html>
    
    This directive defines the following properties for the JSP page:

    • The scripting language is set as Java
    • The buffer size is set to 10 kilo bytes
    • The container will flush the contents if it exceeds the specified size
    • The error page is defined as error.jsp
    • The JSP page may use classes and interfaces from the java.util package within its scriptlets

    The include Directive:-The include directive instructs the container to include the content of a resource in the current JSP during the translation phase. The contents of the included file specified by the directive is included in the including JSP page. For example:

    <%@ include file="filename" %>

    The included file is searched relative to the location of the current JSP unless it is preceded with a forward slash.

    Write this code in notepad and save it include1.jsp. Keep this file in the webapps/jsp folder.
    Code:
    <html>
    <head>
    <title>Include Directive Test Page 1</title>
    </head>
    <body>
    	<h1> Include Directive Test Page 1</h1>
    	<%@ include file="copy.html" %>
    </body>
    </html>
    webapps/jsp/copy.html
    <html>
    <head>
    <title>Included Page</title>
    </head>
    <body>
    <p> &copy; 2010 JSP</p>
    </body>
    </html>
    
    Start Tomcat and go to http://localhost:8080/jsp/expression.jsp

    [​IMG]

    Taglib:- The taglib directive allows the page to use tag extensions(custom tags). It names the tag library that contains compiled Java code defining the tags to be used. The engine uses this tag library to find out what to do when it comes across the custom tags in the JSP.
    The syntax of taglib directive is
    <%@ taglib uri=”tagLibraryURI” prefix=”tagPrefix” %>
    uri= A URI(uniform resource Identifier) that identifies the tag library descriptor.
    Prefix= Defines the prefix string in prefix:tagname that is used to define the custom tag.

    Actions



    Action tag is used to transfer the control between pages and is also used to enable the use of server side JavaBeans. Instead of using Java code, the programmer uses special JSP action tags to either link to a Java Bean set its properties, or get its properties.
    General syntax of Action Tag is:-
    <jsp:action attributes />
    In the above statement jsp is a keyword.

    There are many action tags that are available for Java Server Pages. The most commonly used action tags are three of them and they are namely:

    • Include
    • Forward
    • UseBean

    Syntax, attributes and usage of above three action tags will be given in the next part.

    Continue to JSP Part II
     
    Last edited by a moderator: Jan 21, 2017
  2. shabbir

    shabbir Administrator Staff Member

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

    rameshb New Member

    Joined:
    Dec 10, 2010
    Messages:
    35
    Likes Received:
    1
    Trophy Points:
    0
    wow this is great .. i had so many queries related to JSP most of them are solved here this is great,, site for beginners
     

Share This Page

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