SpringBoot整合SpringMVC
springboot在开发web项目的时候具备天然的优势,现在的很多企业级开发都是依托于springboot的。
使用springboot的步骤:
1、创建一个SpringBoot应用,选择我们需要的模块,SpringBoot就会默认将我们的需要的模块自动配置好
2、手动在配置文件中配置部分配置项目就可以运行起来了
3、专注编写业务代码,不需要考虑以前那样一大堆的配置了。
一、SpringBoot整合Servlet
1、编写Servlet类
编写Servlet类,用来接收浏览器请求
@WebServlet(name = "myServlet",urlPatterns = "/srv")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("111");
super.doGet(req, resp);
}
}
2、配置启动类
在启动类中配置扫描Servlet,以及注册Servlet的bean对象。
@SpringBootApplication
@ServletComponentScan//添加扫描Servlet的注解
public class SpringbootWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootWebApplication.class, args);
}
//将我们的Servlet注册为bean对象,使其启动就生效
@Bean
public ServletRegistrationBean<MyServlet> getServletRegistrationBean(){
ServletRegistrationBean<MyServlet> bean = new ServletRegistrationBean<>(new MyServlet());
bean.setLoadOnStartup(1);
return bean;
}
}
实际工作中我们很少使用Servlet,讲Servlet是为了引出下面的过滤器和监听器。这两个东西是比较常用的。
3、编写Filter
filter也是一个非常重要的模块,比如字符编码过滤器等。要注意过滤器使用了责任链模式,是链式执行的,需要执行chain.doFilter(request, response);判断是否向下执行。
@WebFilter(filterName = "MyFilter", urlPatterns = "/*")//过滤所有请求
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("filter");
chain.doFilter(request, response);
}
@Override
public void destroy() {
System.out.println("destory");
}
}
4、编写Listener
listener是servlet规范定义的一种特殊类,用于监听servletContext,HttpSession和ServletRequest等域对象的创建和销毁事件。监听域对象的属性发生修改的事件,用于在事件发生前、发生后做一些必要的处理。可用于以下方面:
1、统计在线人数和在线用户
2、系统启动时加载初始化信息
3、统计网站访问量
4、记录用户访问路径
public class MyHttpSessionListener implements HttpSessionListener {
public static int online=0;
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("创建session");
online++;
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("销毁session");
}