微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – Spring MVC @RequestMapping不工作

我有一个奇怪的情况,我的控制器不被调用,除非我将调度器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>

这可以按预期工作,我可以请求/休息/用户.但是,如果我将web.xml映射更改为:

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

我得到一个MVC错误

WARN servlet.PageNotFound: No mapping found for HTTP request with URI
[/rest/users] in dispatcherServlet with name ‘rest-servlet’.

看起来真奇怪,因为错误表明请求被映射到调度程序servlet,但是改变的唯一方法是servlet映射.

有没有人遇到这个?

解决方法

dispatcher servlet是Spring MVC的主要servlet.它处理所有请求,来到您的应用程序,并使用自己的路由引擎将其发送到控制器.如果你改变它
<url-pattern>/rest/*</url-pattern>

那么你的请求应该像这样休息/休息/用户

通用模式 – 允许调度servlet处理所有传入的请求(第一个配置是有效的)

原文地址:https://www.jb51.cc/java/122359.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐