25, డిసెంబర్ 2013, బుధవారం

Tutorial: Create JSP custom tag library

http://www.onjava.com/pub/a/onjava/2000/12/15/jsp_custom_tags.html

A Custom tag is a user defined JSP language element. When a JSP page containing custom tag is translated into a Servlet, the tag is converted to operations on an object called tag handler. The Web container then invokes those operations when the JSP page’s servlet is executed. It speeds up web application development because of code reuse feasibility. Custom tags can access all the objects available in JSP pages. Custom tags can modify the response generated by the calling page. Custom tags can be nested.
Custom tag library consists of one or more Java classes called Tag Handlers and an XML tag library descriptor file (tag library).
A class which has to be a tag handler needs to implement Tag interface or IterationTag interface or BodyTag interface or it can also extend TagSupport class or BodyTagSupport class. All the classes that support custom tags are present inside a package called javax.servlet.jsp.tagext.
Let us create a custom tag which will does substring operation on given input. For this we will first create our Tag Handler class. Create a class called SubstrTagHandler and copy/paste following code in it.
package net.viralpatel.jsp.custom.taglib;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class SubstrTagHandler extends TagSupport {
 private String input;
 private int start;
 private int end;
 
 @Override
 public int doStartTag() throws JspException {
  
  try {
   //Get the writer object for output.
   JspWriter out = pageContext.getOut();

   //Perform substr operation on string.
   out.println(input.substring(start, end));

  } catch (IOException e) {
   e.printStackTrace();
  }
  return SKIP_BODY;
 }
 public String getInput() {
  return input;
 }
 public void setInput(String input) {
  this.input = input;
 }
 public int getStart() {
  return start;
 }
 public void setStart(int start) {
  this.start = start;
 }
 public int getEnd() {
  return end;
 }
 public void setEnd(int end) {
  this.end = end;
 }
}
In above code we have created three attributes: input, start and end. These are the inputs that we will get when the custom tag will be invoked from a JSP file. Also note that, these attributes have getter and setter methods which will be used to set the property values.
Now we will create the tag descriptor file also called TLD. Create a file called SubstrDescriptor.tld in WEB-INF directory of your web project and copy / paste following content in it.
<?xml version="1.0" encoding="UTF-8"?>
<taglib> 
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>substr</shortname>
<info>Sample taglib for Substr operation</info>
<uri>http://viralpatel.net/blogs/jsp/taglib/substr</uri>
<tag>
 <name>substring</name>
 <tagclass>net.viralpatel.jsp.custom.taglib.SubstrTagHandler</tagclass>
 <info>Substring function.</info>
 <attribute>
      <name>input</name>
      <required>true</required>
  </attribute>
 <attribute>
      <name>start</name>
      <required>true</required>
  </attribute>
 <attribute>
      <name>end</name>
      <required>true</required>
  </attribute>
</tag>
</taglib> 
In above tld file, <tag> is used to define a custom tag. Each new tag will have its own tag handler class which we specify in <tagclass> tag. Also <name> tag in <tag> represents the tag name that we use in jsp file. We have provided the three attributes with this tag: input, start and end. input is the String whose sub string needs to be parsed. start is the start index and end is the end index.
We have just created our first Custom Taglib for JSP. Now let us use the custom taglib in a JSP file. For this create index.jsp in your web application (if it exists, modify it and add this code) and add following code in it. <required> true make these attribute mandatory.
<%@taglib prefix="test" uri="/WEB-INF/SubstrDescriptor.tld"%>
<html>
<head>
 <title>JSP Custom Taglib example: Substr function</title>
</head>
<body>
 SUBSTR(GOODMORNING, 1, 6) is 
 <font color="blue">
 <test:substring input="GOODMORNING" start="1" end="6"/>
 </font>
</body>
</html>
Following is the screenshot of the output.

jsp 2.0,jsp 2.1 and jsp now 2.2 features

J2EE 1.3: Servlet 2.3, JSP 1.2. JSTL 1.0, ...
J2EE 1.4: Servlet 2.4, JSP 2.0, JSTL 1.1, ...
Java EE 1.5: Servlet 2.5, JSP 2.1, JSTL 1.2

Features of Jsp 2.0
JSP 2.0 is released with new promises. JSP 2.0 is a upgrade version of JSP 1.2 with several new and interesting features. This version is fully compatible with JSP1.2. These features have been added to make the life of web application developers and designers easier. The main objective of the JSP 2.0 is to make JSP easier than ever, it has been made in such a way that it can be learn without the knowledge of Java. After going through this tutorial you will be better understand the features added in JSP 2.0.
The Features in JSP 2.0 are:
  1. Simple Expression Language(EL): Expression Language (EL), provides a way to simplify expressions in JSP. EL provides the ability to use run-time expressions outside JSP scripting elements. Scripting elements are those elements which is used to embed Java code inside the JSP file. Mostly it contains the logic of the program. Scripting elements have three subforms:
    • Declaration: The variables and methods are declared inside declaration. 
    • Scriptlets: The business logic of the program is written inside this. 
    • Expressions: output will be displayed by the expression. 
Expression Language can be enabled in scriptfree JSP pages:
1). By using a page directive: We can enable EL by using

<%@ page isScriptingEnabled="true|false" isEnabled="true|false"%>
2). By using an element of the deployment descriptor:
<jsp-config>
  <jsp-property-group>
  <url-pattern>*.jsp</url-pattern>
  <el-enabled>true</el-enabled>
  <scripting-enabled>true</scripting-enabled>
  </jsp-property-group>
  </jsp-config>
 
  1. JSP Fragments: Jsp fragments is a new feature of JSP 2.0 which allows page author to create custom action fragments that can be invoked. The JSP fragments allows a portion of Jsp code to be encapsulated into a Java object that can be passed around and evaluated zero or more times. Methods for creating a JSP fragment:
    1). Providing the body of a <jsp:attribute>:

    <% attribute name="attributeName" fragment="true">

    2). Providing the body of a tag invocation:
  2. Simple Tag Handlers: 
  3. Easy tags creation with .tag files: With the introduction of JSP 2.0, knowledge of Java is no longer a prerequisite to create a custom tag action. 
  4. Easy Header and Footer template using the prelude and coda includes
 With JSP 2.0 web development has become easy and it also helps in maintaining dynamic web pages easily. To learn JSP 2.0 there is no need to learn java. 

Features of jsp2.1
The main purpose of Java Platform,  Enterprise Edition (Java EE) 5 is to ease development. Now the Jsp2.1 includes the Java Standard Tag Library(JSTL) and JavaServerFaces technology. 
  1. This version has new expression language (EL ) syntax that allows deferred evaluation of expressions. It now enables using the expression to both get and set data and to invoke methods, and facilitates customizing the resolution of a variable or property referenced by an expression.
  2. It supports resource injection through annotations to simplify configuring access to resources and environment data.
  3. It has complete alignment of Jsf technology tags and Jsp software code.  Earlier the version 1.0 of jsf technology depended on jsp 1.2 technology. The reason is that the Jsp 1.2 was already available at the time, and the intension was to make the Jsf 1.0 interface more accessible to a broader audience. As jsp1.2 does not have an integrated expression language and because the Jsp 2.0 EL does not meet all of the needs of Jsf, therefore jsp2.1 was developed to enhance the expression language to meet the needs of Jsf technology.
  4. Qualified functions now take precedence over the ternary operator when the "." operator in use or we can say that ability to redefine the behavior of the "."operator through a Property Resolver API.
  5. EL now supports "literal expressions". The expression which were previously considered to be non-EL value text must now be considered an EL expression.
  6. EL now supports Java 5.0 enumerations.
  7. Ability to plug in Property Resolvers on a per-application and per-page basis.
  8. Ability to express references to bean methods using the expression language and invoking those methods via a Method Binding API.
This version requires these jars:
1) ant-1.6.5.jar
2) core-3.1.1.jar
3 jsp-2.1.jar
4) jsp-api-2.1.jar



Oracle Database 10g SQL (Osborne ORACLE Press Series) - pages from  132-140

Type Inheritance
With the release of the Oracle9 i database, you can use object type inheritance . This allows you to define hierarchies of database types. For example, you might want to define a business person object type and have that type inherit existing attributes from person_typ . The business person type could extend person_typ with attributes to store the person s job title and the name of the company they work for. For person_typ to be inherited from, it must be defined using the NOT FINAL clause:
CREATE TYPE person_typ AS OBJECT (id NUMBER,
 first_name VARCHAR2(10),
 last_name VARCHAR2(10),
 dob DATE,
 phone VARCHAR2(12),
 address address_typ) NOT FINAL;
/
The NOT FINAL clause indicates that person_typ can be inherited from when defining another type. The default is FINAL , meaning that the object type cannot be inherited from.
Note  
I ve provided a SQL*Plus script named object_schema2.sql in the SQL directory that creates a user named object_user2 with a password of object_password . The object_schema2.sql script creates the types, tables, and performs the various INSERT statements shown in the rest of this chapter. You can run the object_ schema2.sql script if you are using an Oracle9 i database or above.
To have a new type inherit attributes and methods from an existing type, you use the UNDER clause when defining your new type. Our example business person type, which I ll name business_person_typ , uses the UNDER clause to inherit the attributes from person_typ :
CREATE TYPE business_person_typ UNDER person_typ (title VARCHAR2(20),
 company VARCHAR2(20));
/
In this example, person_typ is known as the supertype , and business_person_typ is known as the subtype . You can then use business_person_typ when defining column objects or object tables. For example, the following statement creates an object table named object_business_customers :
CREATE TABLE object_business_customers OF business_person_typ;
The following example inserts a row into object_business_customers . Notice that the two additional title and company attributes are supplied:
INSERT INTO object_business_customers VALUES (business_person_typ(1, 'John', 'Brown', '01-FEB-1955', '800-555-1211',
 address_typ('2 State Street', 'Beantown', 'MA', '12345'),
 'Manager', 'XYZ Corp'));
The final example selects this row:

SELECT *FROM object_business_customers;

ID FIRST_NAME LAST_NAME DOB PHONE
---------- ---------- ---------- --------- ------------
ADDRESS(STREET, CITY, STATE, ZIP)
--------------------------------------------------------
TITLE COMPANY
-------------------- --------------------
 1 John Brown 01-FEB-55   800-555-1211 
ADDRESS_TYP('2 State Street', 'Beantown', 'MA', '12345')
Manager XYZ Corp










NOT INSTANTIABLE Object Types
You can mark an object type as NOT INSTANTIABLE , which prevents objects of that type from being created. You might want to mark an object type as NOT INSTANTIABLE when you want to use that type only as a supertype. For example, you could create a type to represent vehicles and use it as a supertype for another type to represent cars and motorcycles. The following statement creates a type named vehicle_typ , which is marked as NOT INSTANTIABLE :
CREATE TYPE vehicle_typ AS OBJECT (id NUMBER,
 make VARCHAR2(15),
 model VARCHAR2(15)) NOT FINAL NOT INSTANTIABLE;
/
Note  
vehicle_typ is also marked as NOT FINAL . A NOT INSTANTIABLE type cannot be FINAL because you wouldn t be able to use it as a supertype, and that s why vehicle_typ is marked as NOT FINAL .
The next example creates a type named car_typ that inherits from the vehicle_typ supertype. Notice car_typ has an additional attribute named convertible that records whether the car is a convertible:
CREATE TYPE car_typ UNDER vehicle_typ (convertible CHAR(1));
/
The following example creates a type named motorcycle_typ that inherits from the vehicle_typ supertype. Notice motorcycle_typ has an additional attribute named sidecar that records whether the motorcycle has a sidecar:
CREATE TYPE motorcycle_typ UNDER vehicle_typ (sidecar CHAR(1));
/
The next example creates tables named vehicles , cars and motorcycles , which are object tables that use the types vehicle_typ , car_typ and motorcycle_typ :
CREATE TABLE vehicles OF vehicle_typ;
CREATE TABLE cars OF car_typ;
CREATE TABLE motorcycles OF motorcycle_typ;
Because vehicle_typ is NOT INSTANTIABLE , you cannot add a row to the vehicles table. If you attempt to do so, the database returns an error; for example:
SQL>

INSERT INTO vehicles VALUES (2  vehicle_typ(1, 'Toyota', 'MR2', '01-FEB-1955')3);

vehicle_typ(1, 'Toyota', 'MR2', '01-FEB-1955') *
ERROR at line 2:ORA-22826: cannot construct an instance of a non instantiable type
The following examples add rows to the cars and motorcycles tables:
INSERT INTO cars VALUES (car_typ(1, 'Toyota', 'MR2', 'Y'));

INSERT INTO motorcycles VALUES (motorcycle_typ(1, 'Harley-Davidson', 'V-Rod', 'N'));
The final example queries the cars and motorcycles tables:

SELECT *FROM cars;

ID MAKE MODEL C
---------- --------------- --------------- -
 1 Toyota MR2 Y

SELECT *FROM motorcycles;

ID MAKE MODEL S
---------- --------------- --------------- -
 1 Harley-Davidson V-Rod N


User-Defined Constructors
Like other object-oriented languages, you can define your own constructors to initialize the attributes of an object. You can define your own constructor to do things like programmatically default one or more attributes of an object.
The following example creates a type named person_typ2 that declares two constructor method signatures:
CREATE OR REPLACE TYPE person_typ2 AS OBJECT (id NUMBER,
 first_name VARCHAR2(10),
 last_name VARCHAR2(10),
 dob DATE,
 phone VARCHAR2(12),
 CONSTRUCTOR FUNCTION person_typ2(p_id NUMBER,
 p_first_name VARCHAR2,
 p_last_name VARCHAR2) RETURN SELF AS RESULT,
 CONSTRUCTOR FUNCTION person_typ2(p_id NUMBER,
 p_first_name VARCHAR2,
 p_last_name VARCHAR2,
 p_dob DATE,
 p_phone VARCHAR2) RETURN SELF AS RESULT);
/
Notice the following about the constructors:
  • The keywords CONSTRUCTOR FUNCTION are used to identify constructors.
  • The keywords RETURN SELF AS RESULT indicate an object of the same type as person_typ2 is returned by each constructor.
  • The first constructor accepts three parameters, and the second constructor accepts five parameters.
The constructor signatures don t contain the actual code bodies for the constructors; the code is contained in the following statement:
CREATE OR REPLACE TYPE BODY person_typ2 AS
 CONSTRUCTOR FUNCTION person_typ2(p_id NUMBER,
 p_first_name VARCHAR2,
 p_last_name VARCHAR2) RETURN SELF AS RESULT IS
 BEGIN
 SELF.id := p_id;
 SELF.first_name := p_first_name;
 SELF.last_name := p_last_name;
 SELF.dob := SYSDATE;
 SELF.phone := '555-1212';
 RETURN;
 END;
 CONSTRUCTOR FUNCTION person_typ2(p_id NUMBER,
 p_first_name VARCHAR2,
 p_last_name VARCHAR2,
 p_dob DATE,
 p_phone VARCHAR2) RETURN SELF AS RESULT IS
 BEGIN
 SELF.id := p_id;
 SELF.first_name := p_first_name;
 SELF.last_name := p_last_name;
 SELF.dob := p_dob;
 SELF.phone := p_phone;
 RETURN;
 END;
END;
/
Notice the following:
  • The constructors use SELF to set the attributes of the object. For example, SELF.id := p_id sets the id attribute of the object to the p_id parameter that is passed to the constructor.
  • The first constructor sets the dob attribute to the datetime returned by the SYSDATE() function, and sets phone to 555-1212. The second constructor simply sets the attributes to the parameters passed to the constructor.
The following example describes person_typ2 :
DESC person_typ2;
Name Null? Type
 ----------------------------------------- -------- -------------------
 ID NUMBER
 FIRST_NAME VARCHAR2(10)
 LAST_NAME VARCHAR2(10)
 DOB DATE
 PHONE VARCHAR2(12)

METHOD
------
 FINAL MEMBER FUNCTION PERSON_TYP2 RETURNS PERSON_TYP2
 Argument Name Type In/Out Default?
 ------------------------------ ----------------------- ------ --------
 P_ID NUMBER IN
 P_FIRST_NAME VARCHAR2 IN
 P_LAST_NAME VARCHAR2 IN

METHOD
------
 FINAL MEMBER FUNCTION PERSON_TYP2 RETURNS PERSON_TYP2
 Argument Name Type In/Out Default?
 ------------------------------ ----------------------- ------ --------
 P_ID NUMBER IN
 P_FIRST_NAME VARCHAR2 IN
 P_LAST_NAME VARCHAR2 IN
 P_DOB DATE IN
 P_PHONE VARCHAR2 IN
You can then create a table of type person_typ2; for example:
CREATE TABLE object_customers2 OF person_typ2;



Summary In this chapter, you learned that
  • The Oracle database allows you to create object types. An object type is like a class in Java.
  • An object type may contain attributes and methods .
  • A simple example of an object type would be a type that models a product. This object type could contain attributes for the product s name , description, and price, along with a method that gets the sell-by date of the product.
  • You create an object type using the CREATE TYPE statement.
  • You can use an object type to define a column in a table, and the column is known as a column object.
  • You can also use an object type to define an entire table, and the table is known as an object table.
  • You use object references to model relationships between object tables, rather than foreign keys. Object references are defined using the REF type and are basically pointers to objects in an object table. Each object in an object table has a unique object identifier (OID) that you can then store in a REF column.
  • With the release of the Oracle9 i database, you can use object type inheritance. This allows you to define hierarchies of database types.
  • You can mark an object type as NOT INSTANTIABLE , which prevents objects of that type from being created. You might want to mark an object type as NOT INSTANTIABLE when you want to use that type as a supertype .
  • You can define your own constructors.
In the next chapter, you ll learn about collections.