2015-04-18 49 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,添加尾部斜线似乎工作。 –