Anda di halaman 1dari 8

JSP directives

The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
There are three types of directives:
page directive
include directive
taglib directive

Syntax of JSP Directive


1. <%@ directive attribute="value" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive


1. <%@ page attribute="value" %>

Attributes of JSP page directive

import
contentType
extends
info
buffer
language
isELIgnored
isThreadSafe
autoFlush
session
pageEncoding
errorPage
isErrorPage

1)import
The import attribute is used to import class,interface or all the members of a package.It is similar
to import keyword in java class or interface.

Example of import attribute


1.
2.
3.
4.
5.
6.
7.
8.

<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>

2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute


1.
2.
3.
4.
5.
6.

<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>

7. </body>
8. </html>

3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.

4)info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.

Example of info attribute


1. <html>
2. <body>
3.
4. <%@ page info="composed by Sonoo Jaiswal" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>
The web container will create a method getServletInfo() in the resulting servlet.For example:
1. public String getServletInfo() {
2. return "composed by Sonoo Jaiswal";
3. }

5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.

Example of buffer attribute


1.
2.
3.
4.
5.
6.
7.
8.

<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

6)language
The language attribute specifies the scripting language used in the JSP page. The default value is
"java".

7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its
value is false i.e. Expression Language is enabled by default. We see Expression Language later.
1. <%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you
can use isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you
make it false, the web container will serialize the multiple requests, i.e. it will wait until the JSP
finishes responding to a request before passing another request to it.If you make the value of
isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
The web container in such a case, will generate the servlet as:
1. public class SimplePage_jsp extends HttpJspBase
2. implements SingleThreadModel{ ....... }

9)errorPage
The errorPage attribute is used to define the error page, if exception occurs in the current page, it
will be redirected to the error page.

Example of errorPage attribute


1. //index.jsp
2. <html>
3. <body>
4.
5. <%@ page errorPage="myerrorpage.jsp" %>
6.
7. <%= 100/0 %>
8.
9. </body>
10. </html>

10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.

Example of isErrorPage attribute


1. //myerrorpage.jsp
2. <html>
3. <body>
4.
5. <%@ page isErrorPage="true" %>
6.
7. Sorry an exception occured!<br/>
8. The exception is: <%= exception %>
9.
10. </body>
11. </html>
Introspection is the automatic process of analyzing a bean's design patterns to reveal the bean's
properties, events, and methods. This process controls the publishing and discovery of bean
operations and properties. This lesson explains the purpose of introspection, introduces the
Introspection API, and gives an example of introspection code.

Purpose of Introspection
A growing number of Java object repository sites exist on the Internet in answer to the demand
for centralized deployment of applets, classes, and source code in general. Any developer who
has spent time hunting through these sites for licensable Java code to incorporate into a program
has undoubtedly struggled with issues of how to quickly and cleanly integrate code from one
particular source into an application.
The way in which introspection is implemented provides great advantages, including:
1. Portability - Everything is done in the Java platform, so you can write
components once, reuse them everywhere. There are no extra specification files
that need to be maintained independently from your component code. There are
no platform-specific issues to contend with. Your component is not tied to one
component model or one proprietary platform. You get all the advantages of the
evolving Java APIs, while maintaining the portability of your components.

2. Reuse - By following the JavaBeans design conventions, implementing the


appropriate interfaces, and extending the appropriate classes, you provide your
component with reuse potential that possibly exceeds your expectations.

Introspection API
The JavaBeans API architecture supplies a set of classes and interfaces to provide introspection.
The BeanInfo (in the API reference documentation) interface of the java.beans package
defines a set of methods that allow bean implementors to provide explicit information about their
beans. By specifying BeanInfo for a bean component, a developer can hide methods, specify an
icon for the toolbox, provide descriptive names for properties, define which properties are bound
properties, and much more.
The getBeanInfo(beanName) (in the API reference documentation) of the Introspector (in
the API reference documentation) class can be used by builder tools and other automated
environments to provide detailed information about a bean. The getBeanInfo method relies on
the naming conventions for the bean's properties, events, and methods. A call to getBeanInfo
results in the introspection process analyzing the beans classes and superclasses.
The Introspector class provides descriptor classes with information about properties, events,
and methods of a bean. Methods of this class locate any descriptor information that has been
explicitly supplied by the developer through BeanInfo classes. Then the Introspector class
applies the naming conventions to determine what properties the bean has, the events to which it
can listen, and those which it can send.
The following figure represents a hierarchy of the FeatureDescriptor classes:

Each class represented in this group describes a particular attribute of the bean. For example, the
isBound method of the PropertyDescriptor class indicates whether a PropertyChangeEvent
event is fired when the value of this property changes.

Customizers
A customizer is a user interface for customizing an entire Bean, as opposed to a single property.
The characteristics and behaviors of the Bean that can be modified by a customizer are not

limited to its exposed properties. There can be any number of other settings that are needed to
configure a Bean that are not considered properties.
The complexity of the configuration options for a Bean is another possible reason to provide a
customizer. This gives you an opportunity to present these choices in a way that makes more
sense to a user, and might even provide a mechanism which can guide the user through the
process.
If you provide a customizer, you must also provide a BeanInfo class for your Bean in order to
identify its associated customizer class. There is no standard naming convention that can be
followed, nor is there any kind of customizer manager class provided by the JDK. This is another
area that seems inconsistent. I dont see any reason why a run-time registration mechanism, like
that provided by the java.beans.PropertyEditorManager, could not have been provided for
registering Bean customizers at run-time. Likewise, I think a naming convention that appends the
string Customizer to the Bean class name would have been useful, allowing for the creation of
customizers without the need for creating a BeanInfo class. However, it is almost trivial to create
a BeanInfo class solely for the purpose of specifying an associated customizer class.

Java Bean
A Java Bean is a java class that should follow following conventions:

It should have a no-arg constructor.


It should be Serializable.
It should provide methods to set and get the values of the properties, known as getter and
setter methods.

Why use Java Bean?


According to Java white paper, it is a reusable software component. A bean encapsulates many objects
into one object, so we can access this object from multiple places. Moreover, it provides the easy
maintenance.

Simple example of java bean class


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.

//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}

17.
18. }

How to access the java bean class?


To access the java bean class, we should use getter and setter methods.

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}

jsp:useBean action tag


1.
2.
3.
4.

jsp:useBean action tag


Syntax of jsp:useBean action tag
Attributes and Usage of jsp:useBean action tag
Simple example of jsp:useBean action tag

The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean
class is already created, it doesn't create the bean depending on the scope. But if object of bean is
not created, it instantiates the bean.

Syntax of jsp:useBean action tag


1.
2.
3.
4.

<jsp:useBean id= "instanceName" scope= "page | request | session | application"


class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>

Attributes and Usage of jsp:useBean action tag


1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be page, request, session or application. The
default scope is page.
o page: specifies that you can use this bean within the JSP page. The default scope is page.
o request: specifies that you can use this bean from any JSP page that processes the same
request. It has wider scope than page.
o session: specifies that you can use this bean from any JSP page in the same session
whether processes the same request or not. It has wider scope than request.
o application: specifies that you can use this bean from any JSP page in the same
application. It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must
have no-arg or no constructor and must not be abstract.
4. type: provides the bean a data type if the bean already exists in the scope. It is mainly used with
class or beanName attribute. If you use it without class or beanName, no bean is instantiated.
5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.

Simple example of jsp:useBean action tag


In this example, we are simply invoking the method of the Bean class.
For the example of setProperty, getProperty and useBean tags, visit next page.

Calculator.java (a simple Bean class)


1.
2.
3.
4.
5.
6.

package com.javatpoint;
public class Calculator{
public int cube(int n){return n*n*n;}
}

index.jsp file
1. <jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
2.
3. <%
4. int m=obj.cube(5);
5. out.print("cube of 5 is "+m);
6. %>
download this example

Let's Create a Simple Bean!


This example is from JavaSoft's "Creating a Minimal Bean."

Step 1: Put this source code into a file named "SimpleBean.java"


import java.awt.*;
import java.io.Serializable;
public class SimpleBean extends Canvas
implements Serializable{
//Constructor sets inherited properties
public SimpleBean(){
setSize(60,40);
setBackground(Color.red);
}
}
What will the above code look like when displayed in the bean box?

Step 2: Compile the file:


javac SimpleBean.java

Step 3: Create a manifest file, named "manifest.tmp":


Name: SimpleBean.class
Java-Bean: True

Step 4: Create the JAR file, named "SimpleBean.jar":


jar cfm SimpleBean.jar manifest.tmp SimpleBean.class

Then verify that the content is correct by the command "jar tf SimpleBean.jar".

Step 5:

1. Start the Bean Box.


CD to c:\Program Files\BDK1.1\beanbox\.
Then type "run".
2. Load JAR into Bean Box by selecting "LoadJar..." under the File menu.

Step 6:
1. After the file selection dialog box is closed, change focus to the "ToolBox" window. You'll see
"SimpleBean" appear at the bottom of the toolbox window.
2. Select SimpleBean.jar.
3. Cursor will change to a plus. In the middle BeanBox window, you can now click to drop in what
will appear to be a colored rectangle.
Your screen should look like this:

Step 7:
Try changing the red box's color with the Properties windows.

Step 8:
Chose "Events" under the "Edit" menu in the middle window to see what events SimpleBean can send.
These events are inherited from java.awt.Canvas.

Let's have fun with our bean... Let's add a property!


As an exercise to try in class right now, let's add a colored rectangle inside of the red square. We'll add a
property named "Color" and give it a setter and a getter method to change the interior rectangle from
its default color of green. The needed code is shown below, so you just have to go through the steps
shown above to make it show up in the Bean Box!
import java.awt.*;
import java.io.Serializable;
public class MediumBean extends Canvas
implements Serializable {
private Color color = Color.green;
//property getter method
public Color getColor(){
return color;
}
//Property setter method. Sets new inside color and repaints.
public void setColor(Color newColor){
color = newColor;
repaint();
}
public void paint(Graphics g) {
g.setColor(color);
g.fillRect(20, 5, 20, 30);
}
//Constructor sets inherited properties
public MediumBean(){
setSize(60,40);
setBackground(Color.red);
}
}

Anda mungkin juga menyukai