我正在尝试将基于web.xml的Web应用程序转换为Spring Boot,但是在配置HttpRequestHandlerServlet时遇到问题。我的web.xml中包含以下内容:
<servlet>
<servlet-name>webServices</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>updateServlet</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>updateServlet</servlet-name>
<url-pattern>/update</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>webServices</servlet-name>
<url-pattern>/ws/*</url-pattern>
</servlet-mapping>
DispatcherServlet不是问题:
@SpringBootApplication
public class WebApplication extends SpringBootServletInitializer
{
public static void main(String[] args)
{
SpringApplication.run(PoolWebApplication.class);
}
@Bean
public DispatcherServlet dispatcherServlet()
{
return new DispatcherServlet();
}
@Bean
public ServletRegistrationBean servletRegistrationBean()
{
return new ServletRegistrationBean(dispatcherServlet(), "/ws/*");
}
}
但是我不知道如何配置updateServlet。
如何在Spring Boot应用程序中配置基于HttpRequestHandlerServlet的servlet?
附加信息:
我尝试了建议的答案,但对我不起作用。
我没有提到的一件事是UpdateServlet被命名为“updateServlet”:
Componenet(“updateServlet”)
公共(public)类UpdateServlet实现HttpRequestHandler
该名称与答案中的Bean名称冲突。更改(更新)后,我得到:
No bean named 'httpRequestHandlerServlet' is defined
将updateServlet的名称更改为httpRequestHandlerServlet之后,我得到了
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'httpRequestHandlerServlet' must be of type [org.springframework.web.HttpRequestHandler], but was actually of type [org.springframework.web.context.support.HttpRequestHandlerServlet]
最佳答案
对于DispatcherServlet
,有一种简单得多的方法,只需在application.properties
中添加一行,然后从您的应用程序类中删除servlet bean。
server.servlet-path=/ws/*
接下来,只需将
HttpRequestHandlerServlet
的定义添加到配置中,而不是DispatcherServlet
即可。@SpringBootApplication
public class WebApplication extends SpringBootServletInitializer
{
public static void main(String[] args)
{
SpringApplication.run(PoolWebApplication.class);
}
@Bean
public HttpRequestHandlerServlet updateServlet()
{
return new HttpRequestHandlerServlet();
}
@Bean
public ServletRegistrationBean updateServletRegistrationBean()
{
return new ServletRegistrationBean(updateServlet(), "/update");
}
}
UPD:
注意,在这里使用
updateServlet()
方法是绝对合法的,并且可以用来获取SpringBean实例(请参见下面的注释)。