Spring mvc @spring中的FormParameter-mvc
在SpringMVC中,我在控制器代码中看到了显式传递的表单参数。为什么要这样做Spring mvc @spring中的FormParameter-mvc,spring-mvc,Spring Mvc,在SpringMVC中,我在控制器代码中看到了显式传递的表单参数。为什么要这样做 public ModelAndView methodXX( @FormParam("arg1") String arg1, @FormParam("arg2") String arg2, @FormParam("arg3") String arg3, HttpServletRequest request, HttpServletResponse res
public ModelAndView methodXX(
@FormParam("arg1") String arg1,
@FormParam("arg2") String arg2,
@FormParam("arg3") String arg3,
HttpServletRequest request, HttpServletResponse response)
如果通话内容如下:
public ModelAndView methodXX(HttpServletRequest request,HttpServletResponse response)
arg1、arg2、arg3仍然可以通过使用
其他参数的request.getParameter(“arg1”)等。
使用FormParam的好处是什么 Spring MVC中没有
@FormParam
注释,至少在我所知道的任何版本中都没有。SpringMVC已经成功了
主要的好处是减少调用中的代码重复
request.getParameter("arg1");
但是,@RequestParam
还有其他参数,即必需的
和默认值
。当required
设置为true
时,如果getParameter
返回null
,Spring将抛出异常。当required
设置为false
时,Spring将调用getParameter
并传递它找到的任何内容,无论它是null
还是实际值
使用defaultValue
,如果getParameter
返回null
,则可以设置默认值
因此,与其这样做
String arg1 = request.getParameter("arg1");
if (arg1 == null) {
arg1 = "default value";
}
您只需添加以下内容作为方法参数
..., @RequestParam(value = "arg1", defaultValue = "default value") String arg1, ...
如果您在请求中使用application/x-www-form-urlencoded内容类型, 您可以在帖子正文中发送数据 method=RequestMethod.POST,consumes=“application/x-www-form-urlencoded” 在这种情况下,POST请求正文中的数据必须采用以下格式 arg1=1&arg2=5&arg3=6 在Chrome浏览器的Postman插件中选择“raw”作为请求主体类型,以测试这一点 还要设置标题: 内容类型应用程序/x-www-form-urlencoded