Saturday, 19 May 2012

JSP

Introduction


Java Server Pages (JSP) is technology which is used for developed the dynamic web applications. JSP provide the easy way to mix the static HTML code with java code, for generate the dynamic web page.
For example:-


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors --> 
<%=request.getParameter("username")%>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for all the rest of the on-line store's Web page.
</BODY></HTML>


Life Cycle of JSP:-

A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:
  1. Translation
  2. Compilation
  3. Loading the class
  4. Instantiating the class
  5. jspInit() invocation
  6. _jspService() invocation
  7. jspDestroy() invocation
Translation: -
In this phase, convert the jsp file in servlet file after validate the JSP syntax.
Compilation: -
In this phase, container compile the generated jsp servlet file and generate the .class file.
Loading the Class: -
After compilation phase, container load the the jsp servlet class file into to servlet container.
Instantiating the class:-
In the execution phase the container manages one or more instances of this class in response to requests and other events.
jspInit() invocation:-
jspInit() method of the javax.servlet.jsp.JspPage interface, is called immediately after the instance was created. It is called only once during JSP life cycle. We can override the jspInit() method in JSP file.
_jspService() Invocation:-
This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.
jspDestroy() invocation:-
The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() methodof servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.

We can override the jspInit() & jspDestroy() method by using the declarations tag. For example:-
<%! public void jspInit() { //code here } %> <%! public void jspDestroy() { //code here } %>

Implicit Objects in JSP:-
JSP has some implicit object. These objects need not be declared or instantiated. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects. The implicit objects available in JSP are as follows:
  1. session (javax.servlet.http.HttpSession)
  2. request(javax.servlet.http.HttpRequestServlet)
  3. response (javax.servlet.http.HttpResponseServlet)
  4. page(java.lang.Object)
  5. out(javax.servlet.jsp.JSPWriter)
  6. application(javax.servlet.ServletContext)
  7. config (javax.servlet.ServletConfig)
  8. pageContext (javax.servlet.jsp.PageContext)
  9. exception (java.lang.Exception)
Introduction to JSP Tags: -

JSP tags can be devided into 4 different types.
  1. Directive:-
    In the directives we can import packages, define error handling pages or the session information of the JSP page.
    Syntax: <%@directive attribute="value" %>
    1. page:-Page directive has number of attributes.
      1. language="java"
        Syntax:- %lt;%@page language="java" %gt;
      2. import="package_name.class_name"
        Syntax:- %lt;%@page language="java" import="java.util.*,com.jsd.beans.User" %gt;
        We can use comma (,) for include more than one pacakges.
      3. session="true"
        By default this session value is true. Session true means data is available to the JSP page otherwise not.
        Syntax: <%@page session="true" %>
      4. errorPage="error.jsp"
        errorPage is used handle the exceptions.
        Syntax: <%@page errorPage="error.jsp"%>
      5. contentType="text/html;charset=ISO-8859-1"
        This attribute is used for set the MIME type and character set of the JSP.
        Syntax: <%page language="java" contentType="text/html;charset=ISO-8859-1"%>
      6. isErrorPage="false" : -false is default value
      7. extends:- used for define the super class of generated servlet.
      8. isThreadSafe="true" :- used for define the threading model for generated servlet.
      9. isELIgnored="false" :-  false is default value. And used for specifies whether or not EL expression within the JSP page will be ignored.
      10. isScriptingEnabled:- Determine if scripting elements are allowed for use.
      11. autoFlush="true": true is default value. Controls the behavior of the servlet output buffer.
      12. buffer="8k": - Specifying a buffering module for output stream.
      13. info:- Defines a string that can be accessed with the servlet's getServletInfo() method.
    2. include:-This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
      Syntax: <%@include file="your_file_location/file_name.jsp"%>
    3. taglib:-The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page.The taglib has 3 attributes uri, prefix & tagdir.
      Syntax:-
      <%@taglib uri="uri" prefix="prefixOfTag" %>
  2. Declarations:-
    This tag is used for defining the functions and variables to be used in the JSP.
    1. <%! //code here %>:- is used for declare the variables and methods in jsp file.
  3. Scriplets:-
    By using this tag, we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine. This is used to contain any code fragment that is valid for the scripting language used in a page. The syntax for a scriptlet is as follows:
    <% scripting-language-statements %>
  4. Expressions:-
    We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream. The syntax for an expression is as follows:
    <%= scripting-language-expression %>


Example how set response type, like pdf:- 
Document document = new Document();
ServletOutputStream ouputStream = null;
try{
response.setContentType("application/pdf");
String submitDate = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
response.addHeader("Content-Disposition", "attachment;filename=AgreementReport_"+submitDate+".pdf" );
ouputStream = response.getOutputStream();


PdfWriter.getInstance(document, ouputStream);
document.open();


headerSection(document,reportHeading,request);// adding top header in PDF
addTitlePage(document,reportName);// add information about PDF
addContents(document,productResults,parameter);// adding contents in PDF
}
catch(Exception e){
utility.getExceptionStack(e);
}
finally{
try {
if(document.isOpen()){
document.close();
}if(ouputStream != null){
ouputStream.flush();
ouputStream.close();
}
} catch (Exception e) {
utility.getExceptionStack(e);
}
}


CREATE COOKIES THROUGH SERVLET
protected void doPost ( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
   IOException {


Cookie cok = new Cookie( "cs", "testing" );
String cookieMSG = null;


String useragent = request.getHeader( "User-Agent" );


String user = useragent.toLowerCase();


// boolean ie, ns6, ns4, netEnabled;
if ( user.indexOf( "msie" ) != -1 ) {
   // ie = true;
   cok.setPath( "/" );
   cok.setMaxAge( 385630 );
   response.addCookie( cok );
   response.setHeader( "P3P", "CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'" );


} else if ( user.indexOf( "netscape6" ) != -1 ) {
   // ns6 = true;
   cok.setPath( "/" );
   cok.setMaxAge( 385630 );
   response.addCookie( cok );


} else if ( user.indexOf( "mozilla" ) != -1 ) {
   // ns4 = true;
   cok.setPath( "/" );
   cok.setMaxAge( 385630 );
   response.addCookie( cok );
}
Cookie[] coki = request.getCookies();
coki = request.getCookies();
if ( coki != null ) {
   for ( Cookie c : coki ) {
if ( c.getName().equalsIgnoreCase( "cs" ) ) {
   cok = new Cookie( "cs", "testing" );
   cok.setPath( "/" );


   cok.setMaxAge( -1 );
   response.addCookie( cok );
   if ( user.indexOf( "msie" ) != -1 ) {
// ie = true;
response.setHeader( "P3P",
"CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'" );


   }
}


   }
   cookieMSG = "ENABLED";
} else {
   cookieMSG = "DISABLED";
}
response.getWriter().print( cookieMSG );
    }

No comments:

Post a Comment