如何使用 Spring Boot 注册 servlet? [英] How can I register a servlet with Spring Boot?
问题描述
此代码无效
我有一个 web.xml 需要翻译成 Spring Boot
I have a web.xml that needs to be translated into a spring boot
<servlet>
<servlet-name>page-resolver</servlet-name>
<servlet-class>com.bk.ForwardServlet</servlet-class>
<init-param>
<param-name>page</param-name>
<param-value>/index.jsp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>page-resolver</servlet-name>
<url-pattern>/index.html</url-pattern>
<url-pattern>/login</url-pattern>
<url-pattern>/qmgr/*</url-pattern>
</servlet-mapping>
还有这个班
@WebServlet
public class ForwardServlet extends HttpServlet {
private String page;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
page = config.getInitParameter("page");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher(page).forward(req, resp);
}
}
我编写了注册此 bean 的代码,但它不起作用,我不明白为什么
I wrote code that registers this bean but it doesn't work and I don't understand why
@Configuration
public class ConfigureWeb implements ServletContextInitializer {
private void registerServlet(ServletContext servletContext) {
ServletRegistrationBean serviceServlet =
new ServletRegistrationBean(new ForwardServlet(), "/index.html","/login","/qmgr/*");
serviceServlet.addUrlMappings("/index.jsp");
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerServlet(servletContext);
}
}
推荐答案
首先检查并确认所有资源都保存在正确的目录中.对于 spring-boot,jsp 页面将保存在目录 <代码>src->main->webapp->WEB-INF->view->*.jsp.
First of all check and verify that all your resources are being kept in the correct directory.For spring-boot the jsp pages are to be kept in the directory src->main->webapp->WEB-INF->view->*.jsp
.
在使用嵌入式tomcat时,您应该在pom中添加以下依赖项以正确编译jsp:
You should have the following dependencies added in pom to compile the jsp properly when using embedded tomcat :
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- To compile JSP files -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
现在我们需要告诉spring jsp文件所在的位置,我们可以有两种方法:
Now we need to tell spring where the jsp files reside, we can have two approaches for this :
在 application.properties 中添加条目
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
这里我们可以指定jsp文件所在的文件夹,以及定义视图.或
Here we can specify the folder where the jsp files are to be expected, as well as define the view. or
配置 InternalResourceViewResolver 以提供 JSP 页面
@Configuration
@EnableWebMvc
@ComponentScan
public class MvcConfiguration extends WebMvcConfigurerAdapter
{
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
registry.viewResolver(resolver);
}
}
现在注册 servlet :
ServletRegistrationBean
用于在 Servlet 3.0 + 容器中注册 Servlet.我们需要在我们的 JavaConfig 中创建一个 ServletRegistrationBean
bean.查找 ServletRegistrationBean 的一些方法,用于配置 Servlet.setServlet(): 设置要注册的 servlet.addUrlMappings(): 为 Servlet 添加 URL 映射.setLoadOnStartup:设置启动时加载 Servlet 的优先级.
ServletRegistrationBean
is used to register Servlets in Servlet 3.0 + container. We need to create a bean of ServletRegistrationBean
in our JavaConfig. Find some methods of ServletRegistrationBean used to configure a Servlet.
setServlet(): Sets the servlet to be registered.
addUrlMappings(): Add URL mappings for the Servlet.
setLoadOnStartup: Sets priority to load Servlet on startup.
假设我们有两个 Servlet,分别是 HelloCountryServlet
和 HelloStateServlet
然后我们将使用 ServletRegistrationBean 向 Spring Boot 注册它们,如下所示:
Suppose we have two Servlets as HelloCountryServlet
and HelloStateServlet
then we will register them with Spring Boot using ServletRegistrationBean as following :
@Configuration
public class WebConfig {
@Bean
public ServletRegistrationBean<HttpServlet> countryServlet() {
ServletRegistrationBean<HttpServlet> servRegBean = new ServletRegistrationBean<>();
servRegBean.setServlet(new HelloCountryServlet());
servRegBean.addUrlMappings("/country/*");
servRegBean.setLoadOnStartup(1);
return servRegBean;
}
@Bean
public ServletRegistrationBean<HttpServlet> stateServlet() {
ServletRegistrationBean<HttpServlet> servRegBean = new ServletRegistrationBean<>();
servRegBean.setServlet(new HelloStateServlet());
servRegBean.addUrlMappings("/state/*");
servRegBean.setLoadOnStartup(1);
return servRegBean;
}
}
我们为每个 Servlet 创建一个 ServletRegistrationBean bean.servlet 类将如下所示:
For every Servlet we create a ServletRegistrationBean bean. And the servlet class will look like :
public class HelloCountryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
doGet(request,response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h3>Hello India!</h3>");
}
}
这是一种方法.
另一种在 spring-boot 中注册 servlet 的方法是使用注解:@ServletComponentScan 和 @WebServlet.Spring Boot 中的 @ServletComponentScan
将扫描用 @WebServlet
注释的 Servlets、用 @WebFilter
注释的过滤器和用 @WebListener注释的监听器代码>.注解@ServletComponentScan在类级别的JavaConfig上使用.@ServletComponentScan 仅使用嵌入式 Web 服务器 来扫描 Servlet、过滤器和侦听器.找到用@WebServlet 注释的 Servlet.
Another method to register servlets in spring-boot is using annotations : @ServletComponentScan and @WebServlet. @ServletComponentScan
in Spring Boot will scan Servlets annotated with @WebServlet
, Filters annotated with @WebFilter
and Listeners annotated with @WebListener
.The annotation @ServletComponentScan is used on JavaConfig at class level. @ServletComponentScan scans Servlets, Filters and Listeners only using an embedded web server. Find the Servlets annotated with @WebServlet.
所以早期的 HelloCountryServlet servlet 可以提供为:
So the earlier HelloCountryServlet servlet can be provided as :
@WebServlet(urlPatterns = "/country/*", loadOnStartup = 1)
public class HelloCountryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
doGet(request,response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h3>Hello India!</h3>");
}
}
并提供 ServletComponentScan 注释,如:
and provide the ServletComponentScan annotation like :
@ServletComponentScan
@SpringBootApplication
public class SpringBootAppStarter {
public static void main(String[] args) {
SpringApplication.run(SpringBootAppStarter.class, args);
}
}
这篇关于如何使用 Spring Boot 注册 servlet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!