springmvc的@RequestMapping、@PathVariable、@RequestParam

springmvc的@RequestMapping、@PathVariable、@RequestParam
    
@RequestMapping("/somepath/{userName}")
public String register(@PathVariable(value = "userName") String userName) {
ModelAndView mav = new ModelAndView();
return "user/createSuccess";
}


在springmvc注解的@RequestMapping("/somepath/{userName}")如何处理默认值的情况,比如我在发送请求的时候,userName有时候是没有的,所以导到了不能匹配这个action
http://localhost:8080/spc/movie/somepath/就不能匹配上面的请求:
http://localhost:8080/spc/movie/somepath/tom而这个才可以匹配。


@PathVariable 会将url中的参数解析到对应的方法参数上,需要在@RequestMapping()指定匹配模式
@RequestMapping("somepath/{userName}")
这时你访问地址"somepath/Tom"就能把"Tom"解析到方法参数userName上


@RequestParam用于将请求参数区数据映射到功能处理方法的参数上
public String requestparam2(@RequestParam("username") String username)
请求中包含username参数(如/requestparam1?username=zhang),则自动传入。

接下来我们看一下@RequestParam注解主要有哪些参数:

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

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

defaultValue:默认值,表示如果请求中没有同名参数时的默认值,默认值可以是SpEL表达式,如“#{systemProperties['java.vm.version']}”。

public String requestparam4(@RequestParam(value="username",required=false) String username)
表示请求中可以没有名字为username的参数,如果没有默认为null,此处需要注意如下几点:


     原子类型:必须有值,否则抛出异常,如果允许空值请使用包装类代替。
     Boolean包装类型类型:默认Boolean.FALSE,其他引用类型默认为null。


public String requestparam5(@RequestParam(value="username", required=true, defaultValue="zhang") String username)
表示如果请求中没有名字为username的参数,默认值为“zhang”。


如果请求中有多个同名的应该如何接收呢?如给用户授权时,可能授予多个权限,首先看下如下代码:
public String requestparam7(@RequestParam(value="role") String roleList)如果请求参数类似于url?role=admin&rule=user,则实际roleList参数入参的数据为“admin,user”,即多个数据之间使用“,”分割;我们应该使用如下方式来接收多个请求参数:
public String requestparam7(@RequestParam(value="role") String[] roleList) 

public String requestparam8(@RequestParam(value="list") List<String> list)  

猜你喜欢

转载自ybianli.iteye.com/blog/1814095