1注解方式实现(较简单)
@WebServlet(name = "MyServlet",urlPatterns = "/rentao")
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print("rentao///////");
}
}
在主类运行入口添加包扫描路径@ServletComponentScan
@SpringBootApplication
@ServletComponentScan(basePackages = "com.qingnian.springboot.servlet")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
2通过配置类管理Servlet对象
public class HeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print("xinba ======");
}
}
配置类:
@Configuration //等价于Spring的xml文件
public class WebConfig implements WebMvcConfigurer {
@Bean //表示返回一个对象
public ServletRegistrationBean getServletBean(){
//第一个参数为对应servlet第二个参数为对应的访问路径
return new ServletRegistrationBean(new HeServlet(),"/heServlet");
}
}