浅谈@RequestMapping注解的注意点

2022-10-18,,

这篇文章主要介绍了浅谈@RequestMapping注解的注意点,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

目录
  • @RequestMapping注解注意点
    • 类上加没加@RequestMappin注解区别
  • @RequestMapping一个坑

    @RequestMapping注解注意点

    类上加没加@RequestMappin注解区别

    1.如果类上加了 @RequestMappin注解,那么就会去该注解对应的路径下去找页面,如果没有对应的页面就会报错。

    举例说明:

    @RequestMapping("/user")
    public class UserController {
        @RequestMapping("/requestParam51")
        public String requestParam51(String[] name) {
           return "index.jsp";
        }
    }

    对应的跳转页面会去user目录下去找,找不到就会报错。

    2.如果类上没有加@RequestMapping注解,就会直接去根路径下去找页面

    3.如果为跳转的页面加了"/",还是会去根路径下去找对应的页面。

    举例:

    @RequestMapping("/user")
    public class UserController {
        @RequestMapping("/requestParam51")
        public String requestParam51(String[] name) {
           return "/index.jsp";
        }
    }

    @RequestMapping一个坑

    今天发现了RequestMapping注解的一个坑:

    当RequestMapping用于Class上时,不能用1.0,v1.0这样带小数点的value值做开头

    @Controller
    @RequestMapping(value = "/v1.0")
    public class TestController {
        @RequestMapping(value = "/a", method = RequestMethod.GET, produces = "application/json")
        public @ResponseBody
        Object getA() {
            return  "{\"test\" : \"a\"}";
        }
        @RequestMapping(value = "/b", method = RequestMethod.GET, produces = "application/json")
        public @ResponseBody
        Object getB() {
            return  "{\"test\" : \"b\"}";
        }
    }

    如上代码运行后,访问http://localhost:port/v1.0/a 或者http://localhost:port/v1.0/b 时都会报错:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'testController' bean method 
    public java.lang.Object com.my.test.controller.TestController.getB()
    to {[/v1.0],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}: There is already 'testController' bean method

    单看异常信息,还以为是有重名的路径,结果搜遍了工程也没找到重名的类,后来"v1.0"改成"v1",就正常运行了。

    顺带测试了下,发现改成1.0也是同样的错误。

    之后再把一个方法上RequestMapping的value去掉,采用默认写法:

        @RequestMapping("/b")
        public @ResponseBody
        Object getB() {
            return  "{\"test\" : \"b\"}";
        }

    再运行起来,访问http://localhost:port/v1.0/a或者http://localhost:port/v1.0/b 就会变成404错误。

    HTTP Status 404 - /v1.0/a
    type Status report
    message /v1.0/a
    description The requested resource is not available.

    没深究根本原因,估计是Spring的小bug,以后避免带小数点的路径头。

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持北冥有鱼。

    您可能感兴趣的文章:

    • SpringMVC @RequestMapping注解详解
    • 类添加注解@RequestMapping报错HTTP Status 404的解决
    • Java工具类之@RequestMapping注解
    • Spring MVC之@RequestMapping注解详解

    《浅谈@RequestMapping注解的注意点.doc》

    下载本文的Word格式文档,以方便收藏与打印。