Jsp Matrial

40
JSP API Introduction 1. Every class which is generated for the JSP must implement eitherjavax.servlet.jsp.JspPage or javax.servlet.jsp .HttpJspPage Interface either directly or indirectly. 2. Tomcat people provided a base classorg.apache.jasper.runtime.HttpJapBase for implementing the above two interfaces. 3. Hence any servlet which is generated by Tomcat is extending theHttpJspBase class. jsp API javax.servlet.jsp.JspPage: JspPage

Transcript of Jsp Matrial

Page 1: Jsp Matrial

JSP API Introduction

1.    Every class which is generated for the JSP must implement eitherjavax.servlet.jsp.JspPage or javax.servlet.jsp.HttpJspPage Interface either directly or indirectly.

2.    Tomcat people provided a base classorg.apache.jasper.runtime.HttpJapBase for implementing the above two interfaces.

3.     Hence any servlet which is generated by Tomcat is extending theHttpJspBase class.

jsp API javax.servlet.jsp.JspPage:

                                      JspPage                                      ======

    <<   - PRIOR                  INDEX                 NEXT   ->>

Introduction:

This interface defines the following two life cycle methods.

Page 2: Jsp Matrial

1.     jspInit()

2.     jspDestroy()

1.jspInit() :

syntax :  public void jspInit()

This method will be executed only once at the time of first request to perform

initialization activities.Web container always calls init(ServletConfig

config) present in HttpJspBase class which intern calls jspInit() method

present in our JSP .

Test.jsp:

<%!

     public void jspInit()

    {

           System.out.println (“my own initialization activities”);

    }

%>

We can’t override init(ServletConfig  config) in our  JSP, because it is

declared as final in parent class (HttpJspBase).

Init() method syntax in HttpJspBase class

public final void  init(javax.servlet.ServletConfig config)

Page 3: Jsp Matrial

                throws javax.servlet.ServletException

HttpJspBase:

<%!

public final void init(serveletconfig config)

{

System.out.println (“my own initialization activities”)’

}

%>

Cannot override the final method from HttpJspBase.

2. jspDestroy():

Syntax: public void jspDestroy()

This method will be executed only once to perform cleanup activities just

before taking JSP from out of service.

Web container always calls destroy()  method present in HttpJspBase  class

which intern calls JspDestroy().

Test.jsp:

<%!

Page 4: Jsp Matrial

   public void jspDestroy(){

      // put your custom code here

      // to clean up resources

   }

%>

We can’t override  destroy() method directly in the JSP.Because it is declared

as the final in HttpJspBase class.

Test.jsp

<%!

public void destroy( )

{

     System.out.println(“my own clean up operations”);

}

%>

C.E: cannot override  the final method from HttpJspBase.

jsp API javax.servlet.jsp.HttpJspBase

Page 5: Jsp Matrial

                                     HttpJspBase                       

    <<   - PRIOR                  INDEX                 NEXT   ->>

javax.servlet.jsp.HttpJspBase

This interface defines only one method :

1.     _jspService( )

Syntax:

public abstract void

_jspService(javax.servlet.http.HttpServletRequest request,

                                 javax.servlet.http.HttpServletResponse response)

                          throws javax.servlet.ServletException,

                                 java.io.IOException

1.     This method will be executed for each client request.

2.     Web container always calls service () method available in HttpJspBase class

which intern calls _jspService() .

3.     We can’t override service () method in our jsp, because it is declared as final

in HtpJspBase class.

4.     Web container will always generate _jspService() in the generated servlet at

the time of translation page.

5.     If we are placing _jspService() method explicitly in jsp then generated

servlet class contains two _jspService() methods which causes compile time

Page 6: Jsp Matrial

error and a  java class never allow to contain more than one method an same

signature. Hence we can’t over ride _ JspService()  method explicitly in the

jsp.

Note:The following three methods are considered as life cycle methods of the

jsp.

1.     jspInit()

2.     jspDestroy()

3.     _jspService()                

How to pre-compile JSP?

Add jsp_precompile as a request parameter and send a request to the JSP file.

This will make the jsp pre-compile. Why it is mentioned as pre compile

instead of compilation is that, the request is not served. That is, the JSP will

not be executed and the request will not be serviced. Just it will be compiled

and the implementation class will be generated.

The jsp_precompile parameter may have no value, or may have values true or

false. It should not have any other values like ?jsp_precompile=yes – this will

result in HTTP error 500.

So the example for query strings to pre compile jsp files are

?jsp_precompile

?jsp_precompile=true

?jsp_precompile=false

?foobar=foobaz&jsp_precompile=true

Page 7: Jsp Matrial

?foobar=foobaz&jsp_precompile=false

The benefits of pre-compiling a JSP page:

It removes the start-up lag that occurs when a container must translate a JSP

page upon receipt of the first request.

Since the Java compiler is not needed, there will be a reduction of the

footprint needed to run a JSP container.

In include directives, tag library references, and translation-time actions used

in custom actions, compilation of a JSP page provides resolution of relative

URL specifications.

How to do pre compile for a bunch of JSP files? for all JSPs

in a folder or application?

There are no special features available for this in the JSP specification. But

the application servers (JSP containers) provide methods to do this on their

own way.

But if you want to pre compile in server independent manner you have to use

jsp_precompile request parameter and no other option available. To do it for

the whole application, you can custome write a servlet or jsp file which will

raise a request for all the JSPs available with jsp_precompi

le added as parameter.

Page 8: Jsp Matrial

1.       JSP container provides a list of objects for you to access different kind of

data in a web application. Those objects are called implicit object because it

is automatically available to access.

2.        These implicit objects are Java objects that implement interfaces in the

Servlet and JSP API. 

There are nine (9) JSP implicit objects available.

Object       Class

  1. request javax.servlet.ServletRequest

  2. response javax.servlet.ServletResponse

  3. application javax.servlet.ServletContext

  4. session javax.servlet.http.HttpSession

  5. page java.lang.Object

  6. config javax.servlet.ServletConfig

  7. exception java.lang.Throwable

  8. pageContext javax.servlet.jsp.PageContext

  9. out javax.servlet.jsp.JspWriter

Note : out & pageContext implicit objects are specially designed for Jsp’s

Implicit objects summary :

1.     Except session and exception implicit objects all are by default available

to every Jsp.

2.     We can’t make them unavailable.

Page 9: Jsp Matrial

3.     But session objects are always available to every Jsp.  But we can make it

unavailable by using session attribute of page directive.

<%@   page session = “false”  %>

4.     Exception implicit object is not available by default but we can make it

available by using isErrorPage of the page directive.

<%@ page isErrorPage = “true” %>

5.     Among all 9 Jsp implicit objects the most powerful object is pageContext.

The most rarely used implicit object is page.

1. request  object

1.     For each request  the JSP engine creates a new object to represents that

request called request object. 

2.     The request object is an instance of  class

javax.servlet.http.HttpServletRequest .

3.     The request object contains all information about the HTTP header, query

string, cookies

4.     Be noted that request object only available in a scope of the current request.

It is re-created each time new request is made.

Methods of request Object:

There are numerous methods available for request Object. Some of them are:

1.getCookies() The getCookies() method of request object returns all

cookies sent with the request information by the client. The

cookies are returned as an array of Cookie Objects.

Page 10: Jsp Matrial

2.getHeader(String name) The method getHeader(String name) of request object is

used to return the value of the requested header.

3.getHeaderNames() The method getHeaderNames() of request object returns all

the header names in the request.

4.getAttribute(String name) The method getAttribute() of request object is used to

return the value of the attribute. The getAttribute() method

returns the objects associated with the attribute.

5.getAttributeNames() The method getAttribute() of request object is used to

return the object associated with the particular given

attribute.

6.getMethod() The getMethod() of request object is used to return the

methods GET, POST, or PUT corresponding to the

requested HTTP method used.

7.getParameter(String name)

getParameter() method of request object is used to return

the value of a requested parameter.

8.getParameterNames() The getParameterNames() method of request object is used

to return the names of the parameters given in the current

request.

9.getParameterValues(String name)

The getParameter(String name) method of request object

was used to return the value of a requested given

parameter.

10.getQueryString() The getQueryString() method of request object is used to

return the query string from the request.

11.getRequestURI() The getRequestURI() method of request object is used for

returning the URL of the current JSP page.

Page 11: Jsp Matrial

12.getServletPath() The getServletPath() method of request object is used to

return the part of request URL that calls the servlet.

13.setAttribute(String,Object)

The setAttribute method of request object is used to set

object to the named attribute.

14.removeAttribute(String) The removeAttribute method of request object is used to

remove the object bound with specified name from the

corresponding session.

Example:

Test.jsp:

<%@ page import = " java.util.* " %>

<html>

<head>

<title>Getting a header in Jsp</title>

</head>

<body>

<%

Enumeration enumeration = request.getHeaderNames();

out.print("<table border= 2>");

while (enumeration.hasMoreElements()) {

String string = (String)enumeration.nextElement();

out.println("<tr><td><h3>" +string +":</h3></td><td><h3> " +

request.getHeader(string)+ "</h3></td></tr>");

Page 12: Jsp Matrial

}

out.print("</table>");

%>

</body>

</html>

Output:

Introduction:1.      response  is an instance of class javax.servlet.http.HttpServletResponse. 

The response object represents the response to the client.

2.      By using this object you can add new cookies, change content type of the

page and redirect the response.

Methods of response Object:

Page 13: Jsp Matrial

There are numerous methods available for response object. Some of them

are:

1.setContentType() setContentType method of response object is

used to set the MIME type and character

encoding for the page.

2.addCookie(Cookie

cookie)

addCookie method of response object is used

to add the specified cookie to the response.

3.addHeader(String name,

String value)

addHeader method of response object is used

to write the header as a pair of name and value

to the response.

4.containsHeader(String

name)

containsHeader method of response object is

used to check whether the response already

includes the header given as parameter.

5.setHeader(String name,

String value)

setHeader method of response object is used to

create an HTTP Header with the name and

value given as string.

6.sendRedirect(String) sendRedirect method of response object is used

to send a redirect response to the client

temporarily by making use of redirect location

URL given in parameter.

7.sendError(int

status_code)

sendError method of response object is used to

send an error response to the client containing

the specified status code given in parameter.

Example: test.jsp

Page 14: Jsp Matrial

<%@ page language="java" %>

<%

response.setContentType("text/html");

response.setHeader("Cache-Control","no-cache");

response.setHeader("Pragma","no-cache");

response.setDateHeader ("Expires", 0);

out.print("Is cache-controle available :"+response.containsHeader("Cache-

Control"));

%>

<html>

<head>

<title>Response object in cache controlling</title>

</head>

</html>

 APPLICATION OBJECT

                                          =====================

   <<   - PRIOR                  INDEX                 NEXT   ->>

Introduction:

1.     The JSP implicit application object is an instance of a java class that

implements the javax.servlet.ServletContext  interface.

2.      It gives facility for a JSP page to obtain and set information about the web

application in which it is running.

Methods of Application Object:

Page 15: Jsp Matrial

There are numerous methods available for Application object. Some of the

methods of Application object are:

1.getAttribute(String name) The method getAttribute of Application

object is used to return the attribute with the

specified name.

2,getAttributeNames The method getAttributeNames of

Application object is used to return the

attribute names available within the

application.

3.setAttribute(String

objName,

Object object)

The method setAttribute of Application

object is used to store the object with the

given object name in the application.

4.removeAttribute(String

objName)

The method removeAttribute of Application

object is used to remove the name of the

object mentioned in parameter of this

method from the object of the application.

5.getMinorVersion() The method getMinorVersion of

Application object is used to return the

minor version of the Servlet API for the JSP

Container.

6.getServerInfo() The method getServerInfo of Application

object is used to return the name and

version number of the JRun servlet engine.

7.getInitParameter(String The method getInitParameter of Application

Page 16: Jsp Matrial

name) object is used to return the value of an

initialization parameter.

8.getInitParameterNames The method getInitParameterNames of

Application object is used to return the

name of each initialization parameter.

9.getResourceAsStream(Path) The method getResourceAsStream of

Application object is used to translate the

resource URL mentioned as parameter in

the method into an input stream to read.

10.log(Message) The method log of Application object is

used to write a text string to the JSP

Container’s default log file.

11.getMajorVersion() The method getMajorVersion of

Application object is used to return the

major version of the Servlet API for the JSP

Container.

Example:

Add this piece of code in web.xml

<context-param>          <param-name>user</param-name>          <param-value>chamu0001</param-value></context-param>

Test.jsp

Page 17: Jsp Matrial

<%@ page session="true" %><%

application.setAttribute("SITE", "MYJAVAHUB.COM");

%><table border= 2><%out.println("<tr><td>Major version: </td><td>" + application.getMajorVersion()+"</td></tr>");out.println("<tr><td>Minor version:</td><td> " + application.getMinorVersion()+"</td></tr>");out.println("<tr><td>Servlet engine version </td><td>" + application.getServerInfo()+"</td></tr>");out.println("<tr><td>User init parameter: </td><td>" +application.getInitParameter("user")+"</td></tr>");out.println("<tr><td>SITE </td><td>" + application.getAttribute("SITE")+"</td></tr>");%></table>

Output:

 SESSION OBJECT                                

      <<   - PRIOR                  INDEX                 NEXT   ->>

Introduction:1.     session object   is an instance of class javax.servlet.http.HttpSession. 

Page 18: Jsp Matrial

2.     The session object is used to store and retrieve client information across the

multiple requests. The session object is not available if the session="false" is

used in page directive.

3.     The previous two objects, request and response, are used to pass information

from web browser to server and from server to web browser respectively. The

Session Object provides the connection or association between the client and

the server.

Methods:

1.getCreationTime This method is used to return the session

created time

2. getLastAccessedTime The getLastAccessedTime method of session

object is used to return the latest time of the

client request associated with the session.

3.getId The getID method of session object is used to

return the unique identifier associated with the

session.

4.invalidate() invalidate method of session object is used to

discard the session and releases any objects

stored as attributes.

5.getMaxInactiveInterval The getMaxInactiveInterval method of session

object is used to return the maximum amount

of time the JRun keeps the session open

between client accesses.

6.setMaxInactiveInterval() This is another setMaxInactiveInterval()

Page 19: Jsp Matrial

method that a developer can use to set the

timeout explicitly for each session.

7.removeAttribute(String

name)

The removeAttribute method of session object

is used to remove the attribute and value from

the session.

8.setAttribute(String,

object)

The setAttribute method of session object is

used to set the object to the named attribute.

Example: test.jsp

<%@ page session="true" %><%session.setMaxInactiveInterval(600);session.setAttribute("SITE", "MYJAVAHUB.COM");

%><table border= 2><%out.println("<tr><td>Created Time of Session is: </td><td>" + session.getCreationTime()+"</td></tr>");out.println("<tr><td>Last Accessed Time of Session is:</td><td> " + session.getLastAccessedTime()+"</td></tr>");out.println("<tr><td>The Session ID is: </td><td>" + session.getId()+"</td></tr>");out.println("<tr><td>Maximum Inactive Interval of Session in Seconds is : </td><td>" +session.getMaxInactiveInterval()+"</td></tr>");out.println("<tr><td>SITE </td><td>" + session.getAttribute("SITE")+"</td></tr>");%></table>

Output :

Page 20: Jsp Matrial

<%@ page session="true" %><%application.setAttribute("SITE", "MYJAVAHUB.COM");%><table border= 2><%out.println("<tr><td>Buffer Size : </td><td>" + out.getBufferSize()+"</td></tr>");out.println("<tr><td>Is AutoFlush Enable</td><td> " + out.isAutoFlush()+"</td></tr>");out.println("<tr><td>Remaining Buffer Size </td><td>" + out.getRemaining()+"</td></tr>");out.println("<tr><td>SITE </td><td>" + application.getAttribute("SITE")+"</td></tr>");%></table>    EXCEPTION OBJECT                                             

   <<   - PRIOR                  INDEX                 NEXT   ->>

exception implicit objects

1.     The JSP implicit exception object is an instance of the java.lang.Throwable class.

2.     JSP gives you an option to specify Error Page for each JSP. Whenever the page throws an exception, the JSP container automatically invokes the error page.

3.     And is only available in error pages. Following is the list of important methods available in the Throwable class..

Methods:

Page 21: Jsp Matrial

1.public String getMessage()

Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.

2. public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object.

3.public String toString()

Returns the name of the class concatenated with the result of getMessage()

4.public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output stream.

5.public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.

6.public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Example: main.jsp

<%@ page errorPage="ShowError.jsp" %><html><head>   <title>Error Handling Example</title></head><body><%   // Throw an exception to invoke the error page

Page 22: Jsp Matrial

   int x = 1;   if (x == 1)   {      throw new RuntimeException("Error condition!!!");   }%></body></html>

ShowError.jsp

<%@ page isErrorPage="true" %><html><head><title>Show Error Page</title></head><body><h1>Opps...</h1><p>Sorry, an error occurred.</p><p>Here is the exception stack trace: </p><pre><% exception.printStackTrace(response.getWriter()); %></pre></body></html>

Output:

java.lang.RuntimeException: Error condition!!!......

Opps...Sorry, an error occurred.

Here is the exception stack trace: EXCEPTION HANDLING                                    

   <<   - PRIOR                  INDEX                 NEXT   ->>

Page 23: Jsp Matrial

We can configure error page in jsp’s by using the following two approaches:1.     Declarative Approach2.     Programmatic Approach

1.     Declarative Approach:

We can configure error pages according to a particular exception (or) according to error code in web.xml as follows.

<web-app>

      <error-page>     <exception-type>java.lang.Throwable</exception-type>     <location>/generalError.jsp</location>      </error-page>

     <error-page>        <error-code>404</error-code>        <location>/exp404.html </location>      </error-page>

 </web-app>

If we are configuring error pages in declarative  approach that error page is applicable for entire application.

 2. Programmatic Approach

We can configure error page for a particular Jsp by using error page attribute of page Directive.

Test.jsp

<% @ page errorPage  = “/Error.jsp” %><h1> The Result is: <% = 10/0 %>

Page 24: Jsp Matrial

Test.jsp  if any exception (or) error occurs then error.jsp is  responsible to report this error.Programmatic Approach error page configuration is applicable only for a particular Jsp.We can declare a Jsp as error page by using isErrorPage attribute of page directive.In this  error pages only exception implicit object is available.

Error.jsp

<%@ page  isErrorPage = “true”  %><h1> can you plz provide valid input <br>The Exception is: <% = exception %> </h1>

If the jsp is not declared as error page then exception implicit object is not available. if we are trying to use we will get compile time error saying Exception cannot be resolved.If we are accessing error page directly without any exception hence exception implicit object refers null.

Which approach is recommended:

Declarative approach is always recommended because we can customize error pages based on exception type (or) error code.  Such type of approach is called Declarative.The following implicit objects are specially designed for Jsp’s.

Note :  All Jsp implicit objects are available as local variables of _jspService().  So  we can use this  implicit objects within _jspService( )  but outside of _jspService() we can’t use , that means we can use inside scriptlet and expression but we can’t use inside declaration  tag.

Example: main.jsp

<%@ page errorPage="ShowError.jsp" %><html><head>

Page 25: Jsp Matrial

   <title>Error Handling Example</title></head><body><%   // Throw an exception to invoke the error page   int x = 1;   if (x == 1)   {      throw new RuntimeException("Error condition!!!");   }%></body></html>

ShowError.jsp

<%@ page isErrorPage="true" %><html><head><title>Show Error Page</title></head><body><h1>Opps...</h1><p>Sorry, an error occurred.</p><p>Here is the exception stack trace: </p><pre><% exception.printStackTrace(response.getWriter()); %></pre></body></html>

Output:

java.lang.RuntimeException: Error condition!!!......

Opps...

Page 26: Jsp Matrial

Sorry, an error occurred.

Here is the exception stack trace: PAGECONTEXT OBJECT                                             

   <<   - PRIOR                  INDEX                 NEXT   ->>

7.pageContext :

1.     pageContext variable is of type javax.servlet.jsp.PageContext.

2.     The PageContext class is the abstract class and JSP engine vendor provides

its concrete subclass.

3.     We can use pageContext implicit object for the following purpose

        To get all other jsp implicit objects

        Provide method to get and set attributes in different scopes.

        Provide convenience methods for transferring request to other resources in

web application.

PageContext.forward(“other.jsp”);

1. Getting Jsp implicit objects from pageContext

     PageContext class defines the following methods for this.

        request                 getRequest ( )        response               getResponse ( )        config                   getServletConfig ( )        application           getServletContext ( )        session                  getSession ( )        out                        getOut ()        page                      getPage ( )        exception              getException ( )

Page 27: Jsp Matrial

These methods are not useful within the Jsp because all implicit objects are available in every Jsp.     But these methods are useful outside the Jsp mostly in custom tag handlers.

2.Attribute Management in any scope

In JSP, pageContext is an implicit object of type PageContext class. The pageContextObject can be used to set, get or remove attribute from one of the following scopes

1.     page2.     request3.     session4.     application

In JSP, page scope is the default scope.

Example:

pageContext.setAttribute("user","myjavahub",PageContext.SESSION_SCOPE);

3.Request Dispatching by pageContext

We can perform Request Dispatching by using pageContext.For this PageContext class defines the following methods.

1.     public void forward (String  target)2.     public void include (String   target)

 PAGE OBJECT

   <<   - PRIOR                  INDEX                 NEXT   ->>

Page implicit object

Page 28: Jsp Matrial

1.     The JSP implicit page object is an instance of the java.lang.Object class. It

represents the current JSP page.

2.      That is, it serves as a reference to the java servlet object that implements the

JSP page on which it is accessed. It is not recommended to us this because it

consumes large memory.

3.     The page object works like “this” key word in java.

4.     In the generated servlet, the variable is declared as follows

     Object page = this;

Parent reference can be used to hold child class object but, by using that

reference we are allow to call only the methods available in the parent class.

Note : page cannot be used to directly call the servlet methods

        page.getServletInfo() Error because page is java.lang.Object type

        ((servlet)page).getServletInfo()        this.getServletInfo()