继承HttpServlet类并且重写doGet和doPost方法
用注解的方式使用Servlet:在Servlet类上加@WebServlet注解
//相当于web.xml配置文件<servlet>标签里的内容
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//向页面中打印SpringBoot Servlet字符串
response.getWriter().print("SpringBoot Servlet");
response.getWriter().flush();
//关闭流
response.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
@ServletComponentScan:扫描指定包下的注解
@SpringBootApplication
@ServletComponentScan(basePackages = "com.why.servlet")
public class Ch06SpringbootServletApplication {
public static void main(String[] args) {
SpringApplication.run(Ch06SpringbootServletApplication.class, args);
}
}
使用配置类方式就无需加@WebServlet注解了
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print("SpringBoot Servlet");
response.getWriter().flush();
response.getWriter().close();
}
}
@Configuration//声明这个类是配置类
public class ServletConfig {
@Bean//注册一个Servlet对象并交给Spring容器管理
public ServletRegistrationBean myServletRegistrationBean(){
ServletRegistrationBean srb = new ServletRegistrationBean(new MyServlet(),"/myServlet2");
return srb;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/m0_60117382/article/details/121581267
内容来源于网络,如有侵权,请联系作者删除!