2015-07-11 133 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应该处理"/"