2013-10-07 114 views
1

我在Eclipse中創建了一個Spring項目。問題在於,URL沒有按照我認爲應該的方式得到解決。未正確解決Spring MVC 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-調度-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 
@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 - 有效輸出 - 「基地」

從我的理解Spring documentation,web.xml中應該將所有/ filestest請求的DispatcherServlet - >這將請求路由到我的控制器 - >它應該匹配正確的方法。

有人可以幫我找出爲什麼我得到404文件沒有找到網址錯誤 - http://mylocalhost.com/filestest/abchttp://mylocalhost.com/filestest/當我嘗試部署和測試我的應用程序?

回答

1

從控制器的RequestMapping註釋中移除/filestest

Spring僅使用映射路徑部分(*),因此不需要在RequestMapping內部具有servlet前綴。

+0

是的。這是原因。因此,看起來,Spring提供了一個URL,將其分解爲與web.xml中匹配「url-mappping」的部分,這些部分與Controller的RequestMapping和方法的RequestMapping相匹配。 – user1700184