[英]POST not supported in custom Servlet as @Bean in Spring Boot
我试图将第3方servlet集成到我的Spring Boot应用程序中,当我尝试将POST提交到servlet时,我在日志中看到以下内容:
PageNotFound: Request method 'POST' not supported
我做了一个简单的测试就可以证明这一点。 我开始使用自动生成的Spring Boot项目 。 然后,我创建了以下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击中端点,如下所示:
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
谢谢!
根据我以前的经验,您必须在结尾处使用斜杠来调用servlet(例如http://localhost:8080/test/
)。 如果不将斜杠放在最后,则请求将路由到映射到/
的servlet,默认情况下是Spring的DispatcherServlet(您的错误消息来自该servlet)。
TestServlet#doPost()
实现调用super.doPost()
-始终发送40x
错误( 405
或400
具体取决于所使用的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!!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.