Declaration in JSP tutorial

Written by admin on . Posted in JSP

As you JSP will compiled in Java file in the end and everything written in JSP will fall under a method(Service) in generated java file. What if you want to add Java code in JSP which should directly be added inside service method in generated file. To fullfil this criteria JSP declaration will be used.

Syntax of JSP Declaration

<%!         %>
Everything written between “<%!” and “%>” will fall inside service method directly without adding any extra line of code.

Example JSP with Declaration

<%@ page import="java.util.*" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%!
    Date dateVariable = new Date();
%>

	<% out.println("Hello"); %>
</body>
</html>

 

Compiled JSP with Declaration Embeded

Welcome_jsp.java

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;

public final class Welcome_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

    Date dateVariable = new Date();

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html; charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("rn");
      out.write("rn");
      out.write("<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">rn");
      out.write("<html>rn");
      out.write("<head>rn");
      out.write("<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">rn");
      out.write("<title>Insert title here</title>rn");
      out.write("</head>rn");
      out.write("<body>rn");
      out.write("rn");
      out.write("rn");
      out.write("rn");
      out.write("t");
 out.println("Hello");
      out.write("rn");
      out.write("</body>rn");
      out.write("</html>");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

 

Write First JSP

Written by admin on . Posted in JSP

Here we will see to write the JSP. And look how this will be converted into Java by container.

Tools/Technology Used

  • Eclipse Indigo
  • Apache Tomcat 7
  • JDK 1.5

We will first create a web application in Eclipse and write a welcome JSP for the same.

Welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<% out.println("Hello"); %>
</body>
</html>

 

This is the JSP which we have created in web application inside WebContent folder. Once we run the web application in Apache Server. Container will generate the Java file for it and then compile it.

Generated Java File for Above JSP /Compiled JSP

Welcome_jsp.java will be the name of generated Java file.

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.30
 * Generated at: 2012-11-03 07:26:27 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class Welcome_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html; charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("rn");
      out.write("<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">rn");
      out.write("<html>rn");
      out.write("<head>rn");
      out.write("<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">rn");
      out.write("<title>Insert title here</title>rn");
      out.write("</head>rn");
      out.write("<body>rn");
      out.write("t");
 out.println("Hello"); 
      out.write("rn");
      out.write("</body>rn");
      out.write("</html>");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

 

Location of precompiled JSP in Tomcat

As we are using Tomcat with Eclipse compiled JSP location can be different according to configuration. To know the exact location of compiled JSP click the Apache server entry in Servers view, it will display the server configuration. In Server Location tab check for the radio button. Here you can set server path and deploy path. You can choose workspace metadata / Tomcat installation directory / Custom location.

To know the exact location of compiled JSP go to

$ServerPathworkCatalinalocalhost$webApplicationName…

ServerPath can be taken from server configuration detail screen. As shown above.

JSP Directive tutorial for Java Beginners

Written by admin on . Posted in JSP

Directive is a type of Statement which can be used to give instruction to container about doing something special at @ page transalation time.

Directive can be divided in three types

  • Page
  • Include
  • Taglib

Page Directive

Syntax of Page Directive

<%@ page import="com.jbt.*"%>

 

Uses of Page Directive

Import Package

Page directive can be used to import single or double package.

Import Single Package

<%@ page import="com.jbt.*"%>

<HTML>
  <BODY>
         Hello! <%= method() %>
  </BODY>
</HTML>

 

Import Multiple Package 

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

<HTML>
  <BODY>
       Hello! <%= method() %>. Time is <%new Date()%>
  </BODY>
</HTML>

 

Taglib Directive

This directive is used to define tag libraries available to JSP.

Syntax of taglib Directive

<%@ taglib tagdir= "" prefix="" %>

 Uses of taglib Directive

taglib directive can be useful in case of Custom tags.

Getting Started with JSP

Written by admin on . Posted in JSP

JSP(Java Server Pages) is a view technology which allows to write template text in client side languages like HTML, CSS, JavaScript and others, instead of Java itself(Which is true for Servlet). To achieve this JSP supports Taglibs(Backed by Java code), Expression Languages and Scriptlet to control theoutput of page.

In the end a JSP becomes Servlet, Servlet which is created by Container and not Developer. So you would require a JSP capable Webserver or Application Server to run a JSP in you application. Stand alone J2SDK is not enough to run JSP.

Different Application Servers

  • Oracle Weblogic
  • IBM WebSphere
  • JBoss
  • Apache Tomcat

Note*: Tomcat is not Application server but a servlet container which can be used for JSP’s.

 

JSP is Servlet(In the end)

When we write a JSP it becomes a Servlet running in web app server. This servlet is same like other Servlet except it is created for you by Container.

Steps Followed by Container

Container follows the given steps in Converting JSP to Servlet.

  1. JSP written by Developer
  2. Container translate this JSP in Servlet Class source file(.Java)
  3. Compiler above Java source file into Java servlet Class.
  4. Loaded and initialized

After above step it is just a Servlet(No JSP) and it runs in the same way as it would have been written as Servlet by developer.

Question: Where different part of JSP will be added in generated Servlet?

Example of Generated Servlet

Actual JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<% out.println("Hello"); %>
</body>
</html>

 Generated Servlet

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class Welcome_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();

  private static java.util.List _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.AnnotationProcessor _jsp_annotationprocessor;

  public Object getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
  }

  public void _jspDestroy() {
  }

  public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html; charset=ISO-8859-1");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("rn");
      out.write("<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">rn");
      out.write("<html>rn");
      out.write("<head>rn");
      out.write("<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">rn");
      out.write("<title>Insert title here</title>rn");
      out.write("</head>rn");
      out.write("<body>rn");
      out.write("t");
 out.println("Hello"); 
      out.write("rn");
      out.write("</body>rn");
      out.write("</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

 

Methods in Generated Servlet

Generated Servlet will have 3 method like Servlets created by developer.

jspInit()

This method is called from init() method. This method can be overriden.

jspDestroy()

This method is called from destroy() method of Servlet. This method can be override.

_jspService()

This method is called from service method of Servlet. This method run in individual thread whenever invoked by request.Container passed the request and response object to this method. This method can not be overriden. But we can control which code will go in this method.

JSP Implicit Object tutorial for Beginners

Written by admin on . Posted in JSP

What is Implicit Object

Implicit Objects are provided by container(to JSP) so that JSP can take advantage of Servletness. First step in JSP life cycle is JSP translation to Servlet. When Container translate JSP in Servlet, it(Container) adds list of declaration and assignment related to implicit Object.

Implicit Object in JSP

In total there are 9 implicit Object in JSP.

  • JspWriter                         : out
  • HttpServletRequest    : request
  • HttpServletResponse : response
  • HttpSession                    : sesion
  • ServletContext              : application
  • ServletConfig                 : config
  • Throwable                       : exception
  • PageContext                   : pageContext
  • Object                                : page

Note*: All of these implicit Objects maps to something from the Servlet/JSP API. 

Out Implicit Object

Out implicit object is a type of jsp.JspWriter. Out can be used to output something in JSP like we use sysout(System.out.println()) in Servlets.

Syntax of Out Implicit Object

<%
out.print("Hello World");
%>

Request Implicit Object

Out implicit object is a type of HttpServletRequest. This object is passed to the service method by the container.

<%= 
     request.getParameter("Email")
%>

 

Response Implicit Object

 

JSP Scriptlet

Written by admin on . Posted in JSP

We can add Java code inside JSP by using JSP expressions. But that part of coding will be the part of service method inside generated JSP. But in case we want to add some code outside service method we need to use JSP scriptlets.

Syntax: <% %>

Example: <%      System.out.println( “Here” ); %>

JSP Expression

Written by admin on . Posted in JSP

Expression is a type of JSP element which is used to embed Java code in JSP. Container takes the argument of expression (everything written between <%=  %>) and put it in as the argument to PrintWriter out which will print on JSP.

Syntax

<%=           scripting-expression            %>

Note* : Semicolon inside expression is not allowed.

Example:

<%= new java.util.Date() %>

Will be converted to

out.println(new java.util.Date());

Above expression can be added to any of JSP. These expressions will be evaluated at run time.

 

Important Point

  • Semicolon is not required while providing statement in Expression.   <%= method(); %> is incorrect
  • Method passed to Expression must return something(Not Void return type) else it will throw an error.