Reputation: 1595
In spring-mvc, in controller code i have seen the form parameters explicitly passed . Why is this done?
public ModelAndView methodXX(
@FormParam("arg1") String arg1,
@FormParam("arg2") String arg2,
@FormParam("arg3") String arg3,
HttpServletRequest request, HttpServletResponse response)
If the call were as follows:
public ModelAndView methodXX(HttpServletRequest request,HttpServletResponse response)
The arg1,arg2,arg3 could still be obtained by using
request.getParameter("arg1") and so on for the others. What is the benefit of using FormParam?
Upvotes: 1
Views: 8061
Reputation: 121
If you use the application/x-www-form-urlencoded content-type in your request, you can send data in the POST body.
method = RequestMethod.POST, consumes = "application/x-www-form-urlencoded"
In this case, the data in POST request body has to be of the format arg1=1&arg2=5&arg3=6
Choose 'raw' for request body type in Postman plugin for Chrome browser, to test this out.
also set the Header: Content-Type application/x-www-form-urlencoded
Upvotes: 0
Reputation: 279880
There is no @FormParam
annotation in Spring MVC, at least not in any version I am aware of. Spring MVC has @RequestParam
.
The main benefit is to reduce the code repetition in calling
request.getParameter("arg1");
However, @RequestParam
also has other parameters, namely required
and defaultValue
. With required
set to true
, Spring will throw exceptions if getParameter
returns null
. With required
set to false
, Spring will call getParameter
and pass whatever it finds, whether it's null
or an actual value.
With defaultValue
, you can set a default value if getParameter
returns null
.
So instead of doing
String arg1 = request.getParameter("arg1");
if (arg1 == null) {
arg1 = "default value";
}
you simply add the following as a method parameter
..., @RequestParam(value = "arg1", defaultValue = "default value") String arg1, ...
Upvotes: 9