2016-03-04 36 views
0

這是Spring的初始化程序。我沒有使用任何.xml文件。控制器寄存器,但返回數據時獲得404

import org.springframework.context.annotation.Configuration; 
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 

import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 

@Configuration 
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     return new Class<?>[]{ 
       WebAppConfig.class, 
       SecurityConfig.class, 
       DatabaseConfig.class, 
       DataSourceGenerator.class, 
       QuartzConfig.class, 
       QueueConfig.class 
     }; 
    } 

    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     super.onStartup(servletContext); 
     servletContext.addFilter(
       "facilityFilter", new FacilityServletFilter() 
     ).addMappingForUrlPatterns(null, false, "/api/*"); 

     servletContext.addFilter(
       "hmacFilter", new HmacFilter() 
     ).addMappingForUrlPatterns(null, false, "/api/*"); 
    } 

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

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     return null; 
    } 
} 

這是我的控制器之一。

@Controller 
@RequestMapping(value = "/install") 
public class HelloController { 

    @RequestMapping(value = "/hi", method = RequestMethod.GET, 
      consumes = "*/*", produces = "text/html") 
    public String sayHello(){ 
     return "<html> <head> <title>API</title>" + 
       "</head>  <body>  <h1>Welcome to the Eric</h1>" + 
       "</body>  </html>"; 
    } 

} 

我所有的其他控制器似乎正常工作,但是當我嘗試打端點這個方法返回一個404錯誤。當我通過Postman調用代碼時,代碼在調試器中被擊中。

回答

0

添加@ResponseBody到控制器方法,否則彈簧會嘗試尋找一個視圖名稱爲"<html> <head> <title>API</title>..."

@Controller 
@RequestMapping(value = "/install") 
public class HelloController { 

    @RequestMapping(value = "/hi", method = RequestMethod.GET, consumes = "*/*", produces = "text/html") 
    @ResponseBody 
    public String sayHello(){ 
     return "<html> <head> <title>API</title>" + 
       "</head>  <body>  <h1>Welcome to the Eric</h1>" + 
       "</body>  </html>"; 
    } 

} 
0

至於建議的Raplh你可以這樣做,但如果你計劃有更多的這些方法可能以及只需將@Controller替換爲@RestController