如何在Spring Boot中注册servlet?

时间:2019-05-04 02:23:49

标签: spring spring-boot servlets

此代码无效

我有一个web.xml,需要将其转换为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的代码,但是它不起作用,我也不明白为什么

@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);
}
}

2 个答案:

答案 0 :(得分:1)

如果您不需要注册servlet,则可以将转发添加到ViewControllerRegistry

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index.html").setViewName("forward:/index.jsp");
        registry.addViewController("/login").setViewName("forward:/index.jsp");
        registry.addViewController("/qmgr/**").setViewName("forward:/index.jsp");
    }
}

您可以使用addViewController模式将三个AntPathMatcher组合为一个

  

将视图控制器映射到给定的URL路径(或模式),以便   使用预先配置的状态代码和视图来呈现响应。

     

“ / admin / **”或“ / articles / {articlename:\ w +}”之类的模式是   允许的。有关语法的更多详细信息,请参见AntPathMatcher

我个人认为将它们分开更容易阅读

答案 1 :(得分:0)

首先检查并确认所有资源都保存在正确的目录中。对于春季启动,jsp页面应保存在目录src->main->webapp->WEB-INF->view->*.jsp中。

您应该在pom中添加以下依赖项,以便在使用嵌入式tomcat时正确地编译jsp:

<!-- 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文件在哪里,我们可以有两种方法:

在application.properties中添加条目

spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

在这里,我们可以指定将要显示jsp文件的文件夹,并定义视图。 或

配置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);
    }
}

现在可以注册 servlets

ServletRegistrationBean用于在 Servlet 3.0 + 容器中注册Servlet。我们需要在JavaConfig中创建一个ServletRegistrationBean的bean。查找用于配置Servlet的ServletRegistrationBean的一些方法。 setServlet():设置要注册的servlet。 addUrlMappings():为Servlet添加URL映射。 setLoadOnStartup:设置启动时加载Servlet的优先级。

假设我们有两个Servlet,分别为HelloCountryServletHelloStateServlet,那么我们将使用ServletRegistrationBean向Spring Boot注册它们,如下所示:

@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类如下所示:

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注释的Servlet,用@WebFilter注释的过滤器和用@WebListener注释的侦听器。@ ServletComponentScan注释在类级别的JavaConfig上使用。 @ServletComponentScan仅使用嵌入式Web服务器 扫描Servlet,过滤器和侦听器。找到用@WebServlet注释的Servlet。

因此,早期的 HelloCountryServlet servlet可以提供为:

@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注释,如:

@ServletComponentScan
@SpringBootApplication
public class SpringBootAppStarter {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootAppStarter.class, args);
    }
}