How to explain usages of square brackets ([]) oper

2019-05-13 16:43发布

问题:

When I read Spring PetClinic sample application, I found they always put the add and modify functionalities into a single JSP file, and they use ${owner['new']} expression to customize elements on current page, for example "New Owner" or "Owner" for a label.

Are there any other usages of [] operator in JSP (Spring) environment?

The Controller file has the following snippet:

@RequestMapping(value = "/owners/new", method = RequestMethod.GET)
public String initCreationForm(Map<String, Object> model) {
    Owner owner = new Owner();
    model.put("owner", owner);
    return "owners/createOrUpdateOwnerForm";
}
@RequestMapping(value = "/owners/{ownerId}/edit", method = RequestMethod.GET)
public String initUpdateOwnerForm(@PathVariable("ownerId") int ownerId, Model model) {
    Owner owner = this.clinicService.findOwnerById(ownerId);
    model.addAttribute(owner);
    return "owners/createOrUpdateOwnerForm";
}

The JSP file has the following snippet:

<h2>
    <c:if test="${owner['new']}">New </c:if> Owner
</h2>

回答1:

The [] will allow you to:

Get a property, if the object is a bean (has getters and setters):

${car['type']}

This will be equivalent to car.getType(); (or car.isType() if the type field is a boolean).

Get a key's value, if the object is a Map:

${carMap['Volvo']}

This will be equivalent to carMap.get('Volvo'); when carMap is a Map.

Get an index, if the object is an array or List:

${cars[1]}

This is equivalent to cars[1] if cars is an array or equivalent to cars.get(1) if cars is a List.

More details/source: http://docs.oracle.com/javaee/6/tutorial/doc/bnahu.html


Edit:

Your question's expression (${owner['new']}) falls into the first case. In the petclinick app, the Owner class is a subclass of Person which is a subclass of BaseEntity. And BaseEntity has a method isNew() (so Owner has that method as well).

This way the snippet ${owner['new']} is equivalent to owner.isNew().



回答2:

Consider following code

bikesMap.put("honda","cbr250r");
bikesMap.put("yamaha","yzfr15");

request.setAttribute("bikesMap",bikesMap);
request.setAttribute("company","honda");

So if we write ${bikesMap["company"] then it will not evaluate to "cbr250r" because what we are providing in [] is a string literal so container will try to find a key "company" which is not present. But if we write ${bikesMap[company]} then this EL will evaulate to "cbr250r".

${bikesMap[compapny]} will evaulate to "cbr250r" because there is a request attribute named company and the value of company i.e. "honda" is a key to the bikesMap.

${bikesMap["company"]} will not evaluate to "cbr250r" because there is no key named "company".

An advantage of [] operator over dot operator is that it can access lists and arrays effectively. You can write ${bikesList["1"]} but you can't write ${bikesList.1}.

Hope this helps