一、使用注解方式
1、使用Servlet3注解方式寫(xiě)一個(gè)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")
二、通過(guò)SpringBoot配置類(lèi)實(shí)現(xiàn)
1山叮、編寫(xiě)一個(gè)普通servlet類(lèi)
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著榴、編寫(xiě)一個(gè)springboot配置類(lèi)
@Configuration
public class ServletConfig {
@Bean
public ServletRegistrationBean heServletRegistrationBean() {
ServletRegistrationBean registration = new ServletRegistrationBean(new HeServlet(),"/heServlet");
return registration;
}
}