SpringBoot使用Servlet简单示例

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");
    }
}
发布了27 篇原创文章 · 获赞 1 · 访问量 851

猜你喜欢

转载自blog.csdn.net/weixin_44971379/article/details/104884130