The <c:set> tag... so much cooler than <jsp:setProperty>

The <jsp:setProperty> tag can do only one thing—set the property of a bean.

But what if you want to set a value in a Map? What if you want to make a new entry in a Map? Or what if you simply want to create a new request-scoped attribute?

You get all that with <c:set>, but you have to learn a few simple rules. Set comes in two flavors: var and target. The var version is for setting attribute variables, the target version is for setting bean properties or Map values. Each of the two flavors comes in two variations: with or without a body. The <c:set> body is just another way to put in the value.

Setting an attribute variable var with <c:set>

  1. With NO body

    image with no caption
  2. WITH a body

    image with no caption

Note

If the value evaluates to null, the variable will be REMOVED! That’s right, removed.

Imagine that for the value (either in the body of the tag or using the value attribute), you use ${person.dog}. If ${person.dog} evaluates to null (meaning there is no person, or person’s dog property is null, then if there IS a variable attribute with a name “Fido”, that attribute will be removed! (If you don’t specify a scope, it will start looking at page, then request, etc.). This happens even if the “Fido” attribute was originally set as a String, or a Duck, or a Broccoli.

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.