SpringBoot整合Servlet的两种方式

1. 注解扫描方式

- 准备Servlet
@WebServlet(name = "firstServlet", urlPatterns = "/firstServlet")  //标记为servlet,以便启动器扫描。
public class FirstServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("firstServlet");
    }

}
- 注册Servlet
@SpringBootApplication
@ServletComponentScan   //启动器启动时,扫描本目录以及子目录带有的webservlet注解的
public class FirstServletApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstServletApplication.class, args);
    }
}

2. 组建注册方式

- 准备Servlet
//这里不需要添加webServlet注解
public class SecondServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().append("SecondServlet");
    }
}

- 注册Servlet
@SpringBootApplication
public class SecondServletApplication {
    public static void main(String[] args) {
        SpringApplication.run(SecondServletApplication.class, args);
    }
    @Bean  //一定要加,不然这个方法不会运行
    public ServletRegistrationBean getServletRegistrationBean() {  //一定要返回ServletRegistrationBean
        ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());     //放入自己的Servlet对象实例
        bean.addUrlMappings("/secondServlet");  //访问路径值
        return bean;
    }
}

给TA打赏
共{{data.count}}人
人已打赏
springboot

springboot项目用maven打包生成的.jar.original是什么?

2022-2-3 18:28:14

未分类

redis redis.conf

2022-5-9 15:51:07

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索