Syntax of jsp:useBean action tag
<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
- id: is used to identify the bean in the specified scope.
- scope: represents the scope of the bean. It may be page, request, session or application. The default scope is page.
- page: specifies that you can use this bean within the JSP page. The default scope is page.
- request: specifies that you can use this bean from any JSP page that processes the same request. It has wider scope than page.
- 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.
- application: specifies that you can use this bean from any JSP page in the same application. It has wider scope than session.
- 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.
- 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.
- 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.
EmployeeData.java
package com.dineshonjava; /** * @author Dinesh Rajput * */ public class EmployeeData { public String getAge(String name){ return "Age of "+name+" is 27 Years"; } public int getSalary(){ return 70000; } public int getArea(int height, int width){ return (height*width); } }
index.jsp
<jsp:useBean id="obj" class="com.dineshonjava.EmployeeData"/> <% String age = obj.getAge("Dinesh Rajput"); out.println(age); %> <br/> <% int salary = obj.getSalary(); out.println("Salary is Rs. "+salary); %> <br/> <% int area = obj.getArea(200, 100); out.println("Area of Home is "+area+" Sq-ft" ); %>
Make a dirctory myapp/com/dineshonjava/ at webapp folder of tomcat server at
C:Program Files (x86)Apache Software FoundationTomcat 7.0webapps
and make class file EmployeeData.class and create index.jsp file with in myapp folder.
Now restart tomcat server and hit the following url.
http://localhost:8080/myapp/index.jsp
Download Example