繁体   English   中英

Spring MVC @RequestMapping无效

[英]Spring MVC @RequestMapping not working

我有一个奇怪的情况,我的控制器不会被调用,除非我将调度程序servlet映射到web.xml中的/ *。 我已经使用RequestMapping定义了一个控制器:

@Controller  
public class UserController {

    @RequestMapping(value = "/rest/users", method = RequestMethod.GET)
    public ModelAndView getUsers(HttpServletRequest request) throws RestException {
      ...
    }  
}

和应用程序上下文:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <context:component-scan base-package="com.test.rest.controller" /> 

最后,这是在web.xml中映射的:

<servlet>
    <servlet-name>rest-servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/restContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>rest-servlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

这按预期工作,即我可以向/ rest / users发出请求。 但是,如果我将web.xml映射更改为:

<servlet-mapping>
    <servlet-name>rest-servlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

我收到一个MVC错误:

WARN servlet.PageNotFound:在名为'rest-servlet'的DispatcherServlet中找不到带有URI [/ rest / users]的HTTP请求的映射。

这似乎很奇怪,因为错误表明请求被映射到dispatcher-servlet,但唯一改变的是servlet映射。

有人遇到过这种情况么?

Dispatcher servlet是Spring MVC的主要servlet。 它处理所有请求,来到您的应用程序,并使用自己的路由引擎将其分派给控制器。 如果你改成它

 <url-pattern>/rest/*</url-pattern>

然后你的请求应该像这个rest/rest/users

常见模式 - 允许调度servlet处理所有传入请求(第一个配置有效)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM