Monday, July 13, 2009

Notes JSP

Notes JSP

Introduction
JSP Directives
Definition
JSP Server - Apache Tomcat
JSP Syntax
JSP Directory Structure
JSP Expression Language and Implicit Objects
JSP output to HTML
JSP Attributes
Tags
JSP Standard Action Tags
Tag library
Example of web.xml file
Errors









Introduction
=============
JSP are
- HTML pages that have Java code embedded.
- server side programs

- JSP have 3 sets of data
1. JSP directives
2. Action Elements
3. Implicit Objects


JSP Directives
===============
Aim: provide information to the JSP container about the page.
<%@ page attributes %>
<%@ include attributes %>
<%@ taglib attributes %>

Page attributes = {import, session, isThreadSafe, Info, errorPage,
isErrorPage, contentType, pageEncoding}

Include attributes = {file}

Definition
==========
Custom Action = tag in the JSP file. Eg. <prefix:name />
Tag Handler = the java class that provides the behaviour of
custom action at run time.



JSP Server - Apache Tomcat
==========================
(see NotesTomcat, NotesGridsphere)

JSP Syntax
==========
Comments
<%-- blah comments --%>
Directives Elements  (JSP style | XML style)
<%@ page attributes %>    | <jsp:directive.page attributes />
<%@ include attributes %> | <jsp:directive.include attributes />
Scripting Elements
<%! declaration %>        | <jsp:declaration> declaration </jsp:declaration>
- can be used to define methods
- variables declared here are available to all code in the same JSP page
<% scriplet code %>       | <jsp:scriplet> code fragment </jsp:scriplet>
- variables declared here are only available in the codelet fragment
<%= expression %>         | <jsp:expression> expression </jsp:expression>
Action Elements (JSP 2.0 specs)
<jsp:useBean>      (creates the bean from a Java Bean class)
<jsp:getProperty>  (uses the getXXX method of JavaBean)
<jsp:setProperty>  (uses the setXXX method of JavaBean)
<jsp:param>
<jsp:include>
<jsp:forawrd>
<jsp:plugin>, <jsp:params>, <jsp:fallback> (used to include JavaBeans or applets)
<jsp:attribute>
<jsp:body>
<jsp:invoke>   (valid for tag libraries)
<jsp:doBody>   (valid for tag libraries)


JSP Directory Structure
=======================
ch03/
  welcome.jsp
  WEB-INF/
     web.xml
     footer.jspf    (a jsp code fragment #included in code)
     errorPage.jsp  (JSP diverts here if there is error)
     tlds/
        (tlds files)
     lib/
        (archives used by application)
     classes/
         ch03/
         FaqCatefories.java
         FaqCatefories.class
        


JSP Expression Language (EL) and Implicit Objects
=============================================
Instead of using JSP scripting elements (see JSP Syntax section),
JSP can use EXPRESSION LANGUAGE (EL) which has a much simpler syntax.
Examples are:
${true}
${"Single quotes in 'double quotes' need not be escaped"}
${2*4}

EL also has implicit objects available to it:
request
response
out
session
config
exception
application

JSP output to HTML
===================
Two ways JSP can output onto html page:

Hello!  The time is now <%= date %>

or

Hello!  The time is now
<%
    // This scriptlet generates HTML output
    out.println( String.valueOf( date ));
%>


JSP Attributes
===============
Each JSP page can have a set of attributes related to the particular page.
Example (developing a tag handler) shows how to interact between a
ClassBean with the member: "topic"
JSP page with attribute: "qid", "question"

1. Structure
ch04/
  TopicList2.jsp
  Questions.jsp
  WEB-INF/
    web.xml
    tlds/
       simplefaq.tld
    classes/
       ch04/
          SimpleList.java
          Questions.java
         
2. Define the class bean:
package ch04
   public class SimpleList extends SimpleTagSupport{
       private String topic;
       public void setTopic(String s) { topic = s; }
       public String getTopic() { return topic; }
      
       public void doTag() throws JspException{
          ......
          getJspContext().setAttribute("qid", topic ....);
          getJspContext().setAttribute("question", topic ....);
          ..........
         
3. define simplefaq.tld
<?xml ....>
<taglib>         
  <tlib-version>...</tlib-version>
  <short-name>  .... </short-name>
  <tag>
    <name>simplelist</a>
    <tag-class>Ch04.SimpleList</tag-class> 
    <body-content>scriptless</body-content>
    <attribute>         // "topic" member of classsBean
      <name>topic</name>
      <required>yes<required>
      <rtexprvalue>yes</rtexprvalue>
    </attribute>
  </tag>
</taglib> 
        
4. define web.xml
<?xml ......>
<web-app>       
  <welcome-file-list>
     <welcome-file>....</....>
  </welcome....>
  <jsp-config>
     <taglib>
        <taglib-uri>/simplequestions</taglib-uri>
        <taglib-location>/WEB-INF/tlds/simplefaq.tld</taglib-location>
     </taglib>
    
     <jsp-property-group>
        <uri-pattern>*.jsp</url-pattern>
<el-enabled>true</el-enabled>
<scripting-enabled>false</scripting-enabled>
     </jsp-property-group>
  </jsp-config>
</web-app>  

5. write the JSP file
<!DOCTYPE....>
<%@ taglib uri="/simplequestions" prefix="faq" %>
<html>
  ....
  <faq:simplelist topic="${param.topic}">
    <a href="Questions.jsp?qid=${qid}"> ${qid} </a>
    ${question} </p>
  </faq:simplelist>
  ....
</html>

....where   
faq - tag library name
simplelist - name of tag
topic - an attribute of the simplelist tag
param.topic - obtained from the bean              
      
            
      


Tags
=====
The following are available in the standard

Interface  <-----  Base Class (Implementing the interface)
=========          ========================================
SimpleTag          SimpleTagSupport
JSPFragment

Simple Tag Handlers = {SimpleTag, JSPFragment} since JSP2.0
Classic Tag Handlers = {Tag, BodyTag, IterationTag} since JSP1.1,1.2


Tag Library Descriptor (TDL) is an xml file
- to inform container which tag handlers are available to JSP pages,
  after creating your own classes that implement a tag.
- configuration file is:
  root/WEB_INF/tlds/descriptor.tld
- descriptor.tld is inside a jar file jarTLD.jar, then store in:
  root/META_INF/jarTLD.jar


JSP Standard Action Tags
=========================
since JSP 2.0
<jsp:xxx>
xxx = {useBean, setProperty, getProperty, param, include, forward,
plugin, params, fallback, attribute, body, invoke, doBody} 

Tag library
============
to create own Tag library
- create a Tag Handler class
    - extends SimpleTagSupport
    - contain get / set methods for data eg. "topic"
    - eg. name of class is SimpleList in package Ch04
   
- create TLD and place in /WEB_INF/tlds/, call it simplefaq.tld
    <taglib>
      .....headers....
  <short-name>simplefaq</short-name>
      <tag>
        <name> simplelist </name>
        <tag-class>Ch04.SimpleList</tag-class>
        <body-content> scriptless</body-content>
        <attribute>
        <name>topic</name>
        <required>yes</required>
        <rtexprvalue>true</rtexprvalue>
        </attribute>
      </tag>
    <taglib> 
   
- create Deployment Descriptor for Tag Library
if using Tomcat, create web.xml with this portion

  <welcomelist>
     <welcome-file>TopicList.jsp</welcome-file>
  </welcomelist>
  <jsp-config>
     <taglib>
        <taglib-uri>/simplequestions</taglib-uri>
        <taglib-location>/WEB-INF/tlds/simplefaq.tld</taglib-location>
     </taglib>
     <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <el-enabled>true</el-enabled>
        <scripting-enabled>false</scripting-enabled>
     </jsp-property-group>
  </jsp-config>

- create JSP file TopicList.jsp
  .....
  <%@ taglib uri="/simplequestions" prefix="faq"%>
  ...... 
     <faq:simplelist topic="${param.topic}">
       ...... ${question}       
     </faq:simplelist>
 


 
using Tag Library:
  create a TLD (Tag Library Descriptor) xml file and fill in details of the tag or class using:
       <tag> ..... </tag>

importing a Tag Libray to use:
   to use a tag library,
       <%@ taglib uri="URI_of_Library" prefix="tag_prefix" %>


- Deploying tag libraries involve:
  i)copy jars and tlds
  ii) add mapping to web.xml
  iii) add a taglib directive to the JSP page, eg:
      <% taglib uri="/portletUI" prefix="ui" %>


- Tag libraries include:
  - JSTL(Sun)
  - Struts(Jakarta) for MVC
  - JNDI (Jakarta) for using Java Naming and Dir Interface
  - BEA Weblogic portal JSP Tag Lib - for working with BEA
  - Coldjava bar Charts - for making graphs
  - Orion EJB - for making EJBs
  -

Example:

1.  Put location of the class in Tag Library Descriptor (TLD)
file in WEB-INF\tlds\portletui.tld
    <tag>
        <name>form</name>
        <tag-class>org.gridlab.gridsphere.provider.portletui.tags.ActionFormTag</tag-class>

2. Specify location of TLD in:   WEB-INF\web.xml
    <taglib>
      <taglib-uri>/portletUI</taglib-uri>
      <taglib-location>/WEB-INF/tlds/portletui.tld</taglib-location>
    </taglib>

3. In JSP file, add the location of the taglib:  
  ****************
<%@ taglib uri="/portletUI" prefix="ui" %>
<%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
<portlet:defineObjects/>
<ui:form>
    Hello, <ui:text beanId="nameTB"/> !
    <ui:textfield size="20" beanId="nameTF"/>
    <ui:actionsubmit action="showName" value="Say Hello!"/>
</ui:form>
   ****************



Example of web.xml file
========================

General part of web.xml
welcome-file: in general tries to load index.html or index.jsp, if not it
    will load from this list of welcome files.
   
*************************
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
   PUBLIC "-//Sun Microsystems, Inc. //DTD Web Application 2.3//EN"
   "http://java.sun.com./dtd/web-app_2_3.dtd">

<web-app>
    <display-name>This is project TomcatTestProject</display-name>
    <description>
This is a simple web application with a source code organization
based on the recommendations of the Application Developer's Guide.
    </description>

  <welcome-file-list>
      <!-- Loads these files as default if no index.html or index.jsp -->
      <welcome-file>index1.html</welcome-file>
      <welcome-file> welcome.jsp </welcome-file>
      <welcome-file>index2.html</welcome-file>
   </welcome-file-list>
</web-app>
******************************
where welcome.jsp is a file in the application.

servlet mappings of general servlet Name, to servlet Class to URL pattern
************************
<servlet>
  <servlet-name>watermelon</servlet-name>
  <servlet-class>myservlets.watermelon</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>watermelon</servlet-name>
  <url-pattern>/fruit/summer/*</url-pattern>
</servlet-mapping>
************************

Errors
=======
The requested resource (/<name>/) is not available.
- make sure that "name" is under webapp subdirectory
- make sure that in "name"'s WEB-INF directory, there is a web.xml
- manually type the URL into the browser like:
    localhost:8090/webAppName/exampleFile.jsp
  then go back to Tomcat Manager, undeploy, then start app again
   
   

No comments: