@RequestParam与@PathVariable

一,@PathVariable

@PathVariable绑定URI模板变量值

@PathVariable是用来获得请求url中的动态参数的

@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上。

/* @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求
* @responsebody表示该方法的返回结果直接写入HTTP response body中
*一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response  body中。
*比如异步获取json数据,加上@responsebody后,会直接返回json数据。
*@Pathvariable注解绑定它传过来的值到方法的参数上
*用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数
*/

    @RequestMapping(value = "newcol/{reportid}/{modelid}", name="querynewcol" , type="design",subtype="custom")
    public ModelAndView querynewcol(HttpServletRequest request ,  @PathVariable String  reportid, 
      @PathVariable String modelid) throws Exception{
     ······
}

二,@RequestParam

在SpringMVC后台控制层获取参数的方式主要有两种,一种是request.getParameter("name"),另外一种是用注解@RequestParam直接获取。

这里主要讲这个注解 @RequestParam,我们看一下@RequestParam注解主要有哪些参数:

value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;

required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报404错误码;

defaultValue:默认值,表示如果请求中没有同名参数时的默认值。

对于url = “${ctx}/main/mm/edit?id=${id}&name=${name}”,
后台:
@RequestMapping("/edit") public String edit(Model model, @RequestParam Map<String, Object> paramMap ) { long id = Long.parseLong(paramMap.get("id").toString()); String name = paramMap.get("name").toString; return page("edit"); }
或者:
@RequestMapping("/edit") public String edit(Model model, @RequestParam long id,@RequestParam String name) { return page("edit"); }
原文地址:https://www.cnblogs.com/caozx/p/10184658.html