一、使用注解方式
1、使用Servlet3注解方式写一个Servlet
@WebServlet(urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = -4316351735748478174L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("my servlet hello world");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
2、在main方法添加注解扫描servlet
@ServletComponentScan(basePackages = "com.example.springboot.servlet")
二、通过SpringBoot配置类实现
1、编写一个普通servlet类
public class HeServlet extends HttpServlet {
private static final long serialVersionUID = -4316351735748478173L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("he servlet hello world");
resp.getWriter().flush();
resp.getWriter().close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
2、编写一个springboot配置类
@Configuration
public class ServletConfig {
@Bean
public ServletRegistrationBean heServletRegistrationBean() {
ServletRegistrationBean registration = new ServletRegistrationBean(new HeServlet(),"/heServlet");
return registration;
}
}
网友评论