2015-04-18 76 views
1

我試圖將第三方servlet集成到我的Spring Boot應用程序中,當我嘗試向servlet提交POST時,我在日誌中看到以下內容:在Spring Boot中不支持自定義Servlet中的@Bean POST

PageNotFound: Request method 'POST' not supported 

我做了一個簡單的測試,顯示這一點。我開始使用auto generated Spring Boot project。然後,我創建了以下的Servlet:

public class TestServlet extends HttpServlet { 
    private static final Logger log = LoggerFactory.getLogger(TestServlet.class); 

    @Override 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
     super.doPost(req, resp); //To change body of generated methods, choose Tools | Templates. 
     log.info("doPost was called!!"); 
    } 

} 

然後我就按照創建的配置,如下所示:

@Configuration 
public class ServletConfig { 
    @Bean //exposes the TestServlet at /test 
    public Servlet test() { 
     return new TestServlet(); 
    }   
} 

然後我跑內Tomcat7的應用。我看到在日誌中:

ServletRegistrationBean: Mapping servlet: 'test' to [/test/] 

然後我試着用捲曲打端點就像這樣:

curl -v http://localhost:8080/test -data-binary '{"test":true}' 

curl -XPOST -H'Content-type: application/json' http://localhost:8080/test -d '{"test":true}' 

我試着加入了@RequestMapping,但那也沒用。任何人都可以幫我弄清楚如何在Spring Boot應用程序中支持另一個Servlet?

你可以在這裏找到示例應用程序:https://github.com/andrewserff/servlet-demo

謝謝!

回答

3

從我以前的經驗來看,你必須在最後用斜線調用servlet(如http://localhost:8080/test/)。如果最後沒有輸入斜線,請求將被路由到映射到/的servlet,默認情況下,Spring的DispatcherServlet(您的錯誤消息來自該servlet)。

+1

修復super.doPost後,嘗試使用真正的測試,它適用於斜線。我覺得自己像個假人......這是一個漫長的深夜! ;) 謝謝! –

2

TestServlet#doPost()實現調用super.doPost() - 這總是發送40x誤差(無論405400取決於所使用的HTTP協議)。

這裏的實現:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException { 

    String protocol = req.getProtocol(); 
    String msg = lStrings.getString("http.method_post_not_supported"); 
    if (protocol.endsWith("1.1")) { 
     resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); 
    } else { 
     resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg); 
    } 
} 

一個Servlet可以通過兩種方式進行註冊: 註冊這個Servlet作爲一個Bean(你的方法 - 這應該是罰款)或 使用ServletRegistrationBean

@Configuration 
public class ServletConfig { 

    @Bean 
    public ServletRegistrationBean servletRegistrationBean(){ 
     return new ServletRegistrationBean(new TestServlet(), "/test/*"); 
    } 
} 

Servlet略有變化:

public class TestServlet extends HttpServlet { 
    private static final Logger log = LoggerFactory.getLogger(TestServlet.class); 

    @Override 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
     // super.doPost(req, resp); 
     log.info("doPost was called!!"); 
    } 
} 
+0

啊,你是正確的,這使我的測試無效!哈哈。不過,我認爲@鄧尼的回答其實是正確的。一旦我刪除super.doPost,添加尾部斜線似乎工作。 –