zoukankan      html  css  js  c++  java
  • SpringMVC注解@RequestMapping的有关探讨

    一  @RequestMapping也可标注在类之前

    标注在类之前,表明所有的请求路径都要基于该路径,如:

    @Controller
    @RequestMapping(path = { "/sys" })
    public class IndexController {
        @RequestMapping("index") 
        public ModelAndView index() {
            System.out.println("index");
            return null;
        }
    }

    执行index()方法的唯一请求路径应为/sys/index。

    二  @RequestMapping的经典异常

    在启动项目时报如下错误,说明在众多请求路径中,有相同的路径。

    //存在两个相同请求路径
    //@RequestMapping("index")
    //@RequestMapping("index")
    java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'indexController' method

    在访问浏览器时报如下错误,说明在众多请求路径中,某一路径集合中的某一路径与其他路径相同。

    //@RequestMapping("index")
    //@RequestMapping(value = { "index" , "main" })
    java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://127.0.0.1:8001/web02/sys/index': 
    {public org.springframework.web.servlet.ModelAndView self.exercise.controller.IndexController.index(),
    public org.springframework.web.servlet.ModelAndView self.exercise.controller.IndexController.index02()}

    三  @RequestMapping的请求方式

    @RequestMapping(path = { "/index" }, method = RequestMethod.POST)
    @RequestMapping(value = { "index" }, method = RequestMethod.GET)

    上面的两个请求路径虽然相同,但是请求的方式不一样,不同请求方式的请求方法执行的方法也不一样。

    HTML只有两种请求方式,如果想处理put或delete请求,应该如何实现?

    首先,在web.xml中配置httpMethodFilter,该过滤器用来处理put和delete请求。

    <filter>
        <filter-name>httpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>httpMethodFilter</filter-name>
        <!--此处的servlet-name值与配置的DispatcherServlet的servlet-name值相同-->
        <servlet-name>petclinic</servlet-name>
    </filter-mapping>

    在JSP页面创建form表单

    <form action="sys/index" method="post">              
        <input type="hidden" value="delete" name="_method">
        <input type="submit" value="提交">                 
    </form>                                              

    Controller:

    @RequestMapping(value = { "index" }, method = RequestMethod.DELETE)

    用这种方式可处理get或delete请求。

    另一种方式是使用JavaScript方法解决。

  • 相关阅读:
    Error: That port is already in use.
    笔记:django is not a registered namespace错误
    笔记:常用SQL语句
    django迁移数据库错误
    OperationalError: (1044, "Access denied for user ''@'localhost' to database 'mydb'")
    笔记:LNMP架构Web的高并发处理
    Debian ZSH解决每次ssh都需要source .bashrc问题
    Django第四天:博客项目实战
    js模板引擎之 Handlebars 基本用法
    创建发布自己的npm包
  • 原文地址:https://www.cnblogs.com/qingyaxuan/p/6504530.html
Copyright © 2011-2022 走看看