SpringMVC RequestParam与PathVariable小结

来源:互联网 发布:mac虚拟机win7镜像下载 编辑:程序博客网 时间:2024/05/29 02:30

RequestParam

@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface RequestParam {    @AliasFor("name")    String value() default "";    @AliasFor("value")    String name() default "";//请求参数名称    //是否必需,默认为true,表示请求参数中必须包含该参数,如果不    //包含抛出异常。    boolean required() default true;    //默认参数值,如果设置了该值自动将required设置为false,如    //果参数中没有包含该参数则使用默认值。    String defaultValue() default ValueConstants.DEFAULT_NONE;}

使用:

@Controllerpublic class HelloController {    @RequestMapping(value = "/test", method = RequestMethod.GET)    public String test(@RequestParam("name") String name) {        System.out.println(name);        return "hello";    }}

PathVariable

当使用@RequestMapping URI占位符映射时,Url中可以通过一个或多个{xxxx}占位符映射,通过@PathVariable可以绑定占位符参数到方法参数中。

@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface PathVariable {    @AliasFor("name")    String value() default "";    @AliasFor("value")    String name() default "";    boolean required() default true;}

使用:

@Controllerpublic class HelloController {    @RequestMapping(value = "/test/{name}", method = RequestMethod.GET)    public String test(@PathVariable("name") String name) {        System.out.println(name);        return "hello";    }}

@PathVariable 注解中的required 属性显得非常鸡肋,目前找到它的一个使用方式:

@Controllerpublic class HelloController {    @RequestMapping(value = {"/test", "/test/{name}"}, method = RequestMethod.GET)    public String test(@PathVariable(value = "name", required = false) String name) {        System.out.println(name);        return "hello";    }}

http://localhost:8080/SpringMVCDemo/test/lghhttp://localhost:8080/SpringMVCDemo/test 都对应于该方法了。


有这样一个问题:
对于@RequestParam("name") String name 以及@PathVariable("name") String name ,注解中的 name 可以省略吗?

想必读者会在自己的IDE中做以上测试了。

当然从测试结果看,有的可以正常工作有的却不可以,报如下异常:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Name for argument type [java.lang.String] not available, and parameter name information not found in class file either.

我在本地使用 IntelliJ IDEA 和 Gradle 搭建的环境下,则可以正常执行。
但是作如下配置就会出错了。

tasks.withType(JavaCompile) {    options.encoding = "UTF-8"    options.debug = false    print '+++++' + options.optionMap() + '+++++'}

也就是把debug模式关闭。
对应于:

javac -g:none //不生成任何调试信息

看来就是debug模式的问题了。

查资料得知:

在正常编译情况下,Java类反射对象是不包含方法的入参名称的。只有在debug模式下才会有参数信息。

参考:
http://www.cnblogs.com/zr520/p/5952874.html
https://stackoverflow.com/questions/9077831/pathvariable-in-spring-controller

原创粉丝点击