2015-07-11 269 views
1

我正在研究基於Spring 4的Java應用程序。此應用程序正在部署到Apache Tomcat。此應用程序運行在URL爲http://localhost:8080/test。我無法使控制器類中定義的GET方法運行。我很確定這是一個配置問題。看看我做錯了什麼?當我在根URL http://localhost:8080/上運行應用程序時,這起作用,但這不適合我。參與第一類:Spring 4與Java配置和沒有xml

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 

public class TestWebInitializer extends  
    AbstractAnnotationConfigDispatcherServletInitializer { 

    @Override 
    protected String[] getServletMappings() { 
     return new String[] { "/test" }; 
    } 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     return new Class<?>[] { RootConfig.class }; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     return new Class<?>[] { WebConfig.class }; 
    } 
} 

涉及第二類:

import static org.springframework.web.bind.annotation.RequestMethod.*; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 

@SuppressWarnings("unused") 
@Controller 
@RequestMapping({"/test"}) 
public class TestController { 

    @RequestMapping(method=GET) 
    public String home() { 
     //TODO: Convert System.out.println to log4j  
     System.out.println("HomeController.home()!"); 

     return "home"; 
    } 
} 
+0

「method = Get」它編譯正確嗎? – Karthik

+0

什麼處理程序方法應該處理URI'http:// localhost:8080 /'? –

+3

您要調用哪個網址「讓GET方法運行」?在你當前的設置中,'TestController#home()'將位於'http:// localhost:8080/test/test'。 – hzpz

回答

0

@hzpz是正確的,getServletMappings() controlls其內您的應用程序上下文路徑得到由servlet處理(而不是在其他Servlet相同的戰爭)。你的配置相匹配的加粗部分:

http://localhost:8080/context_root/test

要更改上下文根,你應該改變戰爭(從ROOT.war)的名稱或更改應用程序服務器的配置文件。

應用程序服務器還會剝離上下文根和servlet映射模式的任何匹配部分,因此,如果您的應用程序正確部署爲http://localhost:8080/test(即上下文根爲/test)的應用程序,則其servlet只會看到路徑在/test之後,所以你的@RequestMapping應該處理"/"