How to set and get properties of a bean in JSP?

In this example you will learn how to set and get the value of Java object properties that you define in a JSP pages. For this example, let’s first start by creating a variable that we named customer, that will have a type of Customer class. To create this variable we use the <jsp:useBean> action.

After we create the customer variable we can set the property value of the customer bean using the <jsp:setProperty> action. And to get the property value of the customer bean we use the <jsp:getProperty> action.

The name attribute in the setProperty and getProperty action refer to our customer bean. The property attribute tells which property we are going to set or get. To set the value of a property we use the value attribute.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>JSP - Bean Property Demo</title>
</head>
<body>

<jsp:useBean id="customer" class="org.kodejava.servlet.support.Customer"/>
<jsp:setProperty name="customer" property="id" value="1"/>
<jsp:setProperty name="customer" property="firstName" value="John"/>
<jsp:setProperty name="customer" property="lastName" value="Doe"/>
<jsp:setProperty name="customer" property="address" value="Sunset Road"/>

Customer Information: <%= customer %><br/>
Customer Name: <jsp:getProperty name="customer" property="firstName"/>
<jsp:getProperty name="customer" property="lastName"/>

</body>
</html>

And here is the code for our Customer bean. This bean contains property such as the id, firstName, lastName and address.

package org.kodejava.servlet.support;

public class Customer {
    private int id;
    private String firstName;
    private String lastName;
    private String address;

    public Customer() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

We access the JSP page we will see the following output:

Customer Information: Customer{id=1, firstName='John', lastName='Doe', address='Sunset Road'}
Customer Name: John Doe
JSP Bean Property Demo

JSP Bean Property Demo

How do I inject collections properties in Spring?

Beside injecting a simple value (using the value attribute) and a reference to other bean (using the ref attribute). We can also inject collections properties into a bean.

Spring provides four ways to inject collections. There are <list> and <set> that can be used to inject arrays or any implementation of java.util.Collection. The <map> that can be used to inject property of type java.util.Map. And the <props> can be used to inject property of type java.util.Properties.

Here is a table that summarize the collection configuration support in Spring.

Collection Element Description
<list> Wiring a list of values, where the values might have duplicates.
<set> Wiring a set of values, where the values can not have duplicates.
<map> Wiring a key-value pairs collection, where the key and value can be any type
<props> Wiring a key-value pairs property, where the key and value are both type of String

You can see the following example on how to use each type of this collection configuration:

How do I wire properties with Spring’s p namespace?

Beside using the <property> element, Spring framework also provide us another way to wiring value or reference into the bean. We can use the Spring’s p namespaces. The p namespace has a schema URI of `http://www.springframework.org/schema/p`.

With this namespace declared in the Spring configuration file you can use the p: prefixed attribute of the <bean> element to wire bean’s property.

We update the configuration used in the previous example How do I inject into bean properties? to use the p namespace. Here is the new Spring’s configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="rectangle" class="org.kodejava.spring.core.Rectangle" />

    <bean id="drawingBean" class="org.kodejava.spring.core.DrawingBean" p:colour="Red" p:shape-ref="rectangle" />

</beans>

The p:color attribute set the color property to Red, this is a simple value. To set the shape property we use the p:shape-ref attribute. The -ref suffix tell Spring that we are injecting a reference.

You can use the <property> element or using the p namespace to inject bean’s property. Both of them have the same functionality.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I inject into bean properties?

A bean usually have some private properties that can be accessed through a pair of accessor methods, the setters and getters. These setters, the setXXX() method can be used by Spring Framework to configure the beans.

This method of injecting beans property through their setter methods is called the setter injection. The following example will show you how to do it.

Below is our DrawingBean that have colour and shape properties. In the example we will inject both of the properties using their respective setter method. The configuration is done in the Spring application configuration file.

package org.kodejava.spring.core;

public class DrawingBean {
    private String colour;
    private Shape shape;

    public DrawingBean() {
    }

    public void drawShape() {
        getShape().draw();
        System.out.printf("The colour is %s.", getColour());
    }

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public Shape getShape() {
        return shape;
    }

    public void setShape(Shape shape) {
        this.shape = shape;
    }
}

We can inject a simple value into a bean, such as string, number, etc. We can also inject a reference to another bean. Here we define an example of other bean, the Rectangle bean that we will inject into the DrawingBean.

package org.kodejava.spring.core;

public interface Shape {
    /**
     * Draw a shape.
     */
    void draw();
}
package org.kodejava.spring.core;

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle.");
    }
}

Let’s create the Spring application configuration file that will register our beans into the Spring context. After that we just create a simple program to execute it.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="rectangle" class="org.kodejava.spring.core.Rectangle" />

    <bean id="drawingBean" class="org.kodejava.spring.core.DrawingBean">
        <property name="colour" value="Red" />
        <property name="shape" ref="rectangle" />
    </bean>

</beans>

In the configuration file above you can see that we use the property element to set a bean’s property. The name attribute is referring to the bean’s setter methods name, exclude the set prefix.

The value attribute of the property element is used to inject a simple value, such as string, int, etc. For injecting a reference to another bean we use the ref attribute instead.

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawingBeanDemo {
    public static void main(String[] args) {
        try (var context = new ClassPathXmlApplicationContext("drawing-bean.xml")) {
            DrawingBean bean = (DrawingBean) context.getBean("drawingBean");
            bean.drawShape();
        }
    }
}

Here are the output of our example:

Drawing a rectangle.
The colour is Red.

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I get Java Home directory?

To get Java Home directory we can obtain it from system properties using the java.home key.

package org.kodejava.lang;

public class JavaHomeDirectory {
    public static void main(String[] args) {
        String javaHome = System.getProperty("java.home");
        System.out.println("JAVA HOME = " + javaHome);
    }
}

On my computer this code give me the following output:

JAVA HOME = C:\Program Files\Java\jdk-17

How do I get the username of operating system active user?

This example show you how to get operating system active user’s login name. We can obtain the username of current user by reading system properties using the user.name key.

package org.kodejava.lang;

public class GettingUserName {
    public static void main(String[] args) {
        String username = System.getProperty("user.name");
        System.out.println("username = " + username);
    }
}

How do I clear system property?

System.clearProperty(String key) method enables you to remove a system property. The key must not be an empty string or a null value because it will cause the method to throw an IllegalArgumentException or a NullPointerException.

It will also check if a SecurityManager exists and if you don’t have a write permission to the system property a SecurityException is going to be thrown.

package org.kodejava.lang;

public class ClearProperty {
    public static void main(String[] args) {
        String key = "user.dir";
        System.out.println(key + " = " + System.getProperty(key));

        // The System.clearProperty() method available since Java 1.5
        System.clearProperty(key);
        System.out.println(key + " = " + System.getProperty(key));
    }
}

The code snippet above give us the following output:

user.dir = F:\Wayan\Kodejava\kodejava-example
user.dir = null

How do I get file separator symbol?

Creating a program to be run on more than one platform such as Windows and Linux our program need to understand the difference between both platform. The simplest thing for instance is the file separator. Windows use "\" (backslash) while Linux use "/" (forward slash).

To avoid manual checking for the operating system we can get the file separator symbol from the system property using the file.separator key.

package org.kodejava.lang;

public class FileSeparatorExample {
    public static void main(String[] args) {
        // file.separator system property return the correct file 
        // separator for each different platform (Windows = \), 
        // (Linux = /)
        String dataFolder = System.getProperty("user.dir") +
                System.getProperty("file.separator") + "data";

        System.out.println("Data Folder = " + dataFolder);
    }
}

How do I read system property as an integer?

The Integer.getInteger() methods allows us to easily read system property and convert it directly to Integer object. This method call the System.getProperty() method and then convert it to integer by calling the Integer.decode() method.

package org.kodejava.lang;

public class IntegerProperty {
    public static void main(String[] args) {
        // Add properties to the system. In this example we create a
        // dummy major and minor version for our application.
        System.setProperty("app.major.version", "2021");
        System.setProperty("app.minor.version", "9");

        // In the code below we use the Integer.getInteger() method to
        // read our application version from the value specified in the
        // system properties.
        Integer major = Integer.getInteger("app.major.version");
        Integer minor = Integer.getInteger("app.minor.version");
        System.out.println("App version = " + major + "." + minor);
    }
}

The output of the code snippet:

App version = 2021.9

How can I get current working directory?

A system properties named user.dir can be used if you want to find the current working directory of your Java program.

package org.kodejava.io;

public class CurrentDirectoryExample {
    public static void main(String[] args) {
        // System property key to get current working directory.
        String USER_DIR_KEY = "user.dir";
        String currentDir = System.getProperty(USER_DIR_KEY);

        System.out.println("Working Directory: " + currentDir);
    }
}

Result example:

Working Directory: F:\Wayan\Kodejava\kodejava-example