Reputation: 89
I'm writing very simple Spring MVC application(just started to learn). It has only one jsp page. After running this application(Im using Tomcat, not big deal) it has to show page with Hello and if I send some parameter to url(for example someURL/?name=mike) it has to be page with Hello mike
here is code
@Controller
@RequestMapping("/")
public class HelloController {
@RequestMapping(method = RequestMethod.GET)
public String printWelcome(@RequestParam("name") String param, ModelMap model) {
if (param == null || param.isEmpty())
model.addAttribute("message", "Hello");
model.addAttribute("message", "Hello " + param);
return "hello";
}
}
and hello.jsp:
<html>
<body>
<h1>${message}</h1>
</body>
</html>
The problem is if I there is not parameter in url, Hello page isnt shown, instead its error
Upvotes: 0
Views: 156
Reputation: 4022
You need to change your method name to include required = false
for the name parameter, otherwise it is required by default, change your method signature to the following:
public String printWelcome( @RequestParam(value = "name", required = false) String param, ModelMap model)
From the Spring documentation:
Parameters using this annotation are required by default, but you can specify that a parameter is optional by setting @RequestParam's required attribute to false (e.g., @RequestParam(value="id", required=false)). http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html
Upvotes: 0
Reputation: 1200
You can set defaultValue
parameter of @RequestParam
. The default value to use as a fallback. Supplying a default value implicitly sets required() to false
.
(@RequestParam(value = "name", defaultValue = "new value")String description)
Upvotes: 0
Reputation: 279960
The @RequestParam
annotation has a required
attribute which you can set to false
(it is true
by default).
public String printWelcome(@RequestParam(value = "name", required = false) String param, ModelMap model) {
only in this case will Spring give you a null
argument to a @RequestParam
annotated parameter.
Upvotes: 1