Spring MVC URL无法正确解析

时间:2013-10-07 03:29:58

标签: spring spring-mvc

我在Eclipse中创建了一个Spring项目。问题是,URL没有以我认为的方式得到解决。

的web.xml

<servlet>
          <servlet-name>mvc-dispatcher</servlet-name>
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
     <servlet-name>mvc-dispatcher</servlet-name>
     <url-pattern>/files/*</url-pattern>
     <url-pattern>/filestest/*</url-pattern>
</servlet-mapping>

这是我的mvc-dispatcher-servlet.xml

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

     <mvc:annotation-driven />
     <context:component-scan base-package="com.github.myproject.controllers" />

</beans>

这是我的Controller文件:

@Controller
@RequestMapping("/filestest")
public class TestController {
    @RequestMapping(value="", method=RequestMethod.GET)
    public @ResponseBody String getBase() {
        System.out.println("Base");
        return "Base";
    }

    @RequestMapping(value="/", method=RequestMethod.GET)
    public @ResponseBody String getRoot() {
        System.out.println("Root");
        return "Root";
    }

    @RequestMapping(value="abc", method=RequestMethod.GET)
    public @ResponseBody String getABC() {
        System.out.println("ABC");
        return "ABC";
    }

    @RequestMapping(value = "/abc", method=RequestMethod.GET)
    public @ResponseBody String getBaseAbc() {
        System.out.println("Base ABC");
        return "Base ABC";
    }

    @RequestMapping(value="/{pathVar}", method=RequestMethod.GET)
    public @ResponseBody String getPathVar(@PathVariable(value="pathVar") String pathVar) {
        System.out.println(pathVar);
        return pathVar;
    }
}

以下是我得到的输出

http://mylocalhost.com/filestest/abc - 404

http://mylocalhost.com/filestest/ - 404

http://mylocalhost.com/filestest - 有效输出 - &#34; Base&#34;

根据我对Spring documentation的理解,web.xml应该将所有/ filestest请求路由到DispatcherServlet - &gt;它将请求路由到我的控制器 - &gt;然后应该匹配正确的方法。

当我尝试部署和测试我的应用程序时,有人可以帮我弄清楚为什么我在获取404文件时找不到网址错误 - http://mylocalhost.com/filestest/abchttp://mylocalhost.com/filestest/

1 个答案:

答案 0 :(得分:1)

从控制器的/filestest注释中删除RequestMapping

Spring只使用映射的路径部分(*),因此不需要在RequestMapping中包含servlet前缀。