Getting the Value of Bean

Using Bean in JSP Page(jsp:useBean tag)

Java Beans are java objects that have properties,which can be read via a get method or changed via a set method.A java bean should not have any public variables. All the variables should be accessed using the getter/setter methods.

Let us create a class Employee which will be used in JSP page .Employee class is an example of a basic bean.

What is a Java Bean ?

Java Beans are java objects that have properties,which can be read via a get method or changed via a set method.A java bean should not have any public variables. All the variables should be accessed using the getter/setter methods.

Let us create a class Employee which will be used in JSP page .Employee class is an example of a basic bean.

package com.javawebtutor.jsp; public class Employee < private String name; private String department; public String getName() < return name; >public void setName(String name) < this.name = name; >public String getDepartment() < return department; >public void setDepartment(String department) < this.department = department; >>

How to use java beans in a JSP file ?

In JSP we can use java beans using Tag.The jsp:useBean element instantiates an object of the class specified by class and binds it to a variable with the name specified by ID.

Читайте также:  Opening file with python

Syntax of jsp:useBean action tag :

 id= "instanceName" scope= "page | request | session | application" class= "packageName.className" type= "packageName.className" beanName="packageName.className |  expression >" > jsp:useBean> 
  • id :Holds the unique name that is assigned to the bean
  • type: Is an optional attribute,which specifies the type of the class.
  • class: is the class name of the bean.
  • beanName: Is the name of bean as supplied to the instantiate() method in java.beans.Beans class.
  • scope: Indicates the context in which the bean should be made available.There are four types of scope available. page: This is default scope which indicates that the bean is only available on the current page.The bean can be used within the JSP page with the jsp:useBean tag or any other static include files until the page sends a response back or forwards request to another resource.
    request: The value of this object indicates that the bean is available for the current client request.The bean can be used within the JSP page processing the same request until a jsp page sends a response back or forwards request to another resource.
    session: The value of this object indicates that the bean is available to all pages during that share the same ServletContext.In other words the bean can be used from any jsp page in the same application.
    application: The value of this object indicates that the bean is only available for the current client request.The bean can be used within the JSP page processing the same request until a jsp page sends a response back or forwards request to another resource.

Following JSP standard actions is required to use Java bean in a JSP file.

Load Java bean inside a JSP :

To start working with java beans inside a jsp page ,the bean should be available into the page. Once the bean is available in jsp,the variable or properties of the bean can be accessed.

In above syntax Employee class is instantiated and binding it to a variable name specified in the » id » attribute.

Writing above syntax in a JSP page creates an object referencing to the class Employee and the name of the object is employee .

Getting the Properties of the Bean :

After the bean gets loaded into the page, the properties can be accessed using the standard actions.

The basic syntax of the is as follows:

The above syntax tells the compiler to get the value of the variable » name » of the object » employee «. The attribute name in the above syntax represents the object created using the action. The value of the name attribute of the and the id attribute of the property should be same.

For getting all the properties of the bean inside the jsp page the syntax of the should be

Example of :

Step 1: Create Java Bean :

Create a java class inside com.javawebtutor.jsp package in eclipse and assign the name of the class as Employee .Declare and initialize two string variables » name » and » department «.

package com.javawebtutor.jsp; public class Employee < private String name = "Mukesh"; private String department = "Development"; public String getName() < return name; >public void setName(String name) < this.name = name; >public String getDepartment() < return department; >public void setDepartment(String department) < this.department = department; >>

Step 2 : Create a jsp page

Create a jsp page inside WebContet directory of the project and name it as index.jsp . Get the value of java Bean variable using tag.

         

Employee details is mentioned below


Browser Output :

JSP useBean Action

Example of :

To modify (or) assign value to any variable of the bean object standard action is used . The basic syntax is as below

Step 1: Create Java Bean :

Create a java class inside com.javawebtutor.jsp package in eclipse and assign the name of the class as Employee .Declare and initialize two string variables » name » and » department «.

package com.javawebtutor.jsp; public class Employee < private String name; private String department; public String getName() < return name; >public void setName(String name) < this.name = name; >public String getDepartment() < return department; >public void setDepartment(String department) < this.department = department; >>

Step 2 : Create JSP Page:

Create a jsp page index.jsp and Load the bean using the action and name the bean as » employee » using the » id » attribute.

Set the properties of the bean using the and Print the variables again using the to check the new values of the bean.Code of index.jsp is given below.

           

Employee Details


Источник

JSP — JavaBeans

A JavaBean is a specially constructed Java class written in the Java and coded according to the JavaBeans API specifications.

Following are the unique characteristics that distinguish a JavaBean from other Java classes −

  • It provides a default, no-argument constructor.
  • It should be serializable and that which can implement the Serializable interface.
  • It may have a number of properties which can be read or written.
  • It may have a number of «getter» and «setter» methods for the properties.

JavaBeans Properties

A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can be of any Java data type, including the classes that you define.

A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed through two methods in the JavaBean’s implementation class −

For example, if property name is firstName, your method name would be getFirstName() to read that property. This method is called accessor.

For example, if property name is firstName, your method name would be setFirstName() to write that property. This method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have only a setPropertyName() method.

JavaBeans Example

Consider a student class with few properties −

package com.tutorialspoint; public class StudentsBean implements java.io.Serializable < private String firstName = null; private String lastName = null; private int age = 0; public StudentsBean() < >public String getFirstName() < return firstName; >public String getLastName() < return lastName; >public int getAge() < return age; >public void setFirstName(String firstName) < this.firstName = firstName; >public void setLastName(String lastName) < this.lastName = lastName; >public void setAge(Integer age) < this.age = age; >>

Accessing JavaBeans

The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable that can be accessed by both scripting elements and other custom tags used in the JSP. The full syntax for the useBean tag is as follows −

Here values for the scope attribute can be a page, request, session or application based on your requirement. The value of the id attribute may be any value as a long as it is a unique name among other useBean declarations in the same JSP.

Following example shows how to use the useBean action −

     

The date/time is

You will receive the following result − −

The date/time is Thu Sep 30 11:18:11 GST 2010

Accessing JavaBeans Properties

Along with action, you can use the action to access the get methods and the action to access the set methods. Here is the full syntax −

The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean action. The property attribute is the name of the get or the set methods that should be invoked.

Following example shows how to access the data using the above syntax −

         

Student First Name:

Student Last Name:

Student Age:

Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the following result will be displayed −

Student First Name: Zara Student Last Name: Ali Student Age: 10

Источник

Компонент JavaBean

Компоненты JavaBean – это многократно используемые классы Java, позволяющие разработчикам существенно ускорять процесс разработкии WEB-приложений путем их сборки из программных компонентов. JavaBeans и другие компонентные технологии привели к появлению нового типа программирования – сборки приложений из компонентов, при котором разработчик должен знать только сервисы компонентов; детали реализации компонентов не играют никакой роли.

JavaBean – это одноуровневые объекты, использующиеся для того, чтобы инкапсулировать в одном объекте код, данные или и то и другое. Компонент JavaBean может иметь свойства, методы и события, открытые для удаленного доступа.

Методы getters setters

Компонент JavaBean должен удовлетворять определенным соглашениям о наименовании методов и экспортируемых событий. Одним из важных понятий технологии JavaBeans является внешний интерфейс properties (свойства). Property JavaBean – это методы getters setters, обеспечивающие доступ к информации о внутреннем состоянии компонента JavaBean.

Для обращения к компонентам JavaBeans на странице JSP необходимо использовать следующее описание тега в разделе head :

Идентификатор BeanID определяет имя компонента JavaBean, являющееся уникальным в области видимости, определенной атрибутом scope. По умолчанию принимается область видимости scope=»page», т.е. текущая страница JSP.

Обязательный атрибут класса компонента «class» может быть описан следующим способом:

класса" [type="полное имя суперкласса"]

Свойства JavaBean — jsp:setProperty jsp:getProperty

Свойство JavaBean компонента устанавливается тегом jsp:setProperty. Пример :

Для чтения свойства компонента JavaBean с именем myBean используется тег jsp:getProperty :

В следующем листинге приведен пример компонента JavaBean, содержащего строку mystr, используемую в качестве свойств компонента. В компоненте определены методы getter setter.

package beans; public class myBean < private String mystr; //---------------------------------------------- public String getMystr() < return mystr; >//---------------------------------------------- public void setMystr(String mystr) < this.mystr = mystr; >//---------------------------------------------- >

Синтаксис описания компонента JavaBean на странице JSP приведен на странице Действия actions JSP

Пример использования JavaBean на странице JSP

Рассмотрим простой пример, в котором на странице JSP будет выведено приветствие из JavaBean компонента. Для разработки будет использована IDE Eclipse. На следующем скриншоте представлена структура проекта JavabeanExample, включающего компонент JavaBeanHello.java, страницу index.jsp и дескриптор приложения.

Листинг JavaBean компонента JavaBeanHello.java

Компонент включает свойстве message и методы get/set.

package example; public class JavabeanHello < private String message = "JavaBean компонент приветствует Вас!"; public JavabeanHello() <>public String getMessage() < return message; >public void setMessage(final String message) < this.message = message; >>

Листинг дескриптора приложения web.xml

Дескриптор приложения не включает никакой информации о JavaBean компоненте, используемый на страницах WEB-приложения.

Листинг JSP страницы index.jsp

     %>     $ Сегодня  

На странице определена кодировка UTF-8 и выполняется импорт утилит и классов для работы с датой. Тег определяет JavaBean компонент — класс, область видимости (page) и alias использования на странице. Для вывода на страницу сообщения компонента указывается его alias и свойство «$».

Интерфейс страницы представлен на следующем скриншоте.

Курсивом на страницу выведена строка с текущей датой и временем.

Скачать примеры

Исходные коды проекта JavaBeanExample, рассмотренного в тексте страницы, можно скачать здесь (7 Кб).

Источник

Оцените статью