springboot与servlet
-
servlet3.0+
-
直持注解和配置两种方式注册
-
定义一个类继承HttpServlet,加上注解**@WebServlet("/xxx")** xxx就是访问时的接口名
@WebServlet("/one")
public class OneServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("springboot servlet!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
- 在主类中加上@ServletComponentScan(“xxx”) xxx就是需要注册的类所在的位置
@SpringBootApplication
@ServletComponentScan("com.ssp.controller.OneServlet")
public class SpringbootFirstApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootFirstApplication.class, args);
}
}
- servlet2.5+
- 只支持配置方式
- 无需添加任何注解。取消@WebServlet和@ServletComponentScan注解
- 在主类中添加@Bean方法
public class SpringbootFirstApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootFirstApplication.class, args);
}
//2.5+以后使用的配置方式实现
@Bean
public ServletRegistrationBean<OneServlet> oneServlet(){//OneServlet是用于注册的那个Servlet类
return new ServletRegistrationBean<>(new OneServlet(),"/one");//(new OneServlet(),"接口")
}
}