码迷,mamicode.com
首页 > 编程语言 > 详细

springboot整合Servlet

时间:2019-05-11 14:50:40      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:info   exception   实例化   Servle   att   string   cal   let   add   

一.整合servlet

1.通过注解扫描完成Servlet组件的注解

1.1 编写servlet

/**
 * SpringBoot整合servlet方式一
 * 以往实在web.xml配置
 * <servlet>
 * <servlet-name>FirstServlet</servlet-name>
 * <servlet-class>com.demo.servlet.FirstServlet</servlet-class>
 * </servlet>
 * <p>
 * <sevlet-mapping>
 * <servlet-name>FirstServlet</servlet-name>
 * <url-patter>/first</url-patter>
 * </sevlet-mapping>
 */
//注意继承的是 import javax.servlet.http.HttpServlet;
@WebServlet(name = "FirstServlet", urlPatterns = "/first")
public class FirstServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       System.out.println("FirstServlet........................");
    }
}

1.2 编写启动类

/**
 * springboot整合servlet方式一
 */
@SpringBootApplication
@ServletComponentScan //在springboot启动时会扫描@WebServlet注解,并将该类实例化
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

1.3启动 运行main方法  在浏览器输入http://localhost:8080/ifrst 返回控制台

技术图片

2.通过方法完成servlet组件的注解

2.1 编写servlet

/**
 * springboot整合servlet方式二
 */
public class SecondServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("SecondServlet...........");

    }
}

2.2编写启动器

/**
 * springboot整合servlet方式二
 */
@SpringBootApplication
public class App2 {
    public static void main(String[] args) {
        SpringApplication.run(App2.class,args);
    }

    /**
     * ServletRegistrationBean是注册servlet的对象
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean getServletRegistrationBean() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
        bean.addUrlMappings("/second");
        return bean;
    }
}

以下如上

小结: springboot整合servlet有两种方式:

1.注解:@WebServlet @SpringBootApplication @ServletComponentScan

2.方法:@Application ServletRegisterBean addUrlMapping @Bean

 

springboot整合Servlet

标签:info   exception   实例化   Servle   att   string   cal   let   add   

原文地址:https://www.cnblogs.com/wangshuang123/p/10848583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!