Working with variables by using c:set and c:remove actions

JSTL provides c:set action to initialize or set a variable of the web application in a specific scope. The usage of the c:set is as follows:

In the var attribute, you can declare or refer to a variable. The value attribute specifies the value of the variable. If you want to set the scope of the variable, you can use the scope attribute. The scope attribute accepts any valid JSP variable scopes such as page, request, session, and application.

Let’s take a look at an example of using  c:set action.

In the example, we set the variable userid to 10 with the session scope. Then we print it out using c:out action.

The other usage of  c:set action is to set the value of a property of an object:

You assign an object to the target attribute, property name to the property attribute and value of that property in the value attribute.

Let’s take a look at an example of using c:set for setting a property of an object.

In the above code, we have a person class. We will use this person class as a JavaBean in a JSP page.

In the code above, we use the standard action useBean to initialize an object person. Then we use  c:set to set the firstName and lastName property of that object. We display the fullName of  the person object to the web browser.

Notice that that in the target attribute, only object is accepted therefore you should not forget the expression  ${object_name}

Beside c:set action, JSTL also provides c:remove action that allows you to remove a variable from a particular scope. The syntax of c:remove is action is as follows:

For example, if you want to remove the userid session variable you can use c:remove as follows:
  • Was this tutorial helpful ?
  • YesNo