When using the ${}
syntax, you are in fact using Spring Expression Language (SpEL). There are several variants of EL available in the wild; SpEl is one of the most powerful variants.
Here is an overview of its main features:
Feature |
Syntax |
Explanation |
---|---|---|
Accessing a list element |
| |
Accessing a map entry |
| |
Ternary operator |
| |
Elvis operator |
|
Returns |
Safe navigation |
|
Returns |
Templating |
|
Injects values into a string |
Projections |
|
Extracts the names of all the persons and puts them into a list |
Selection |
|
Retrieves the person whose name is Bob inside a list |
Function call |
|
For complete reference, check the manual at http://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html.
The SpEl usage is not limited to views. You can also use it in various places inside the Spring framework, for instance, when injecting properties inside beans with the @Value
annotation.
We are able to display data coming from the server inside the view. However, what if we wanted to get input from the user? With the HTTP protocol, there are multiple ways to do this. The simplest way is to pass a query parameter to our URL.
We can leverage this technique to ask our user for their name. Let's modify our HelloController
class again:
@Controller public class HelloController { @RequestMapping("/") public String hello(@RequestParam("name") String userName, Model model) { model.addAttribute("message", "Hello, " + userName); return "resultPage"; } }
If we navigate to localhost:8080/?name=Geoffroy
, we can see the following:
By default, the request parameter is mandatory. This means that if we were to navigate to localhost:8080
, we would see an error message.
Looking at the @RequestParam
code, we can see that in addition to the value parameter, there are two other attributes possible: required
and defaultValue
.
Therefore, we can change our code and specify a default value for our parameter or indicate that it is not required:
@Controller public class HelloController { @RequestMapping("/") public String hello(@RequestParam(defaultValue = "world") String name, Model model) { model.addAttribute("message", "Hello, " + name); return "resultPage"; } }