Java | Spring框架学习笔记--(4)MVC框架整合
发布日期:2021-05-07 23:15:27 浏览次数:18 分类:原创文章

本文共 2453 字,大约阅读时间需要 8 分钟。

MVC框架整合

为什么要整合MVC框架?

  1. MVC框架提供了控制器(Controller)调用Service
  2. 请求响应的处理
  3. 接受请求参数 request.getParameter(" ")
  4. 控制程序的运行流程
  5. 视图解析(JSP、JSON、Freemarker、Thyemeleaf)

环境搭建

  1. 新建一个Maven的项目/模块,骨架选择列表里的webapp

  2. 导入依赖

        <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.11</version>      <scope>test</scope>    </dependency>    <dependency>      <groupId>javax.servlet</groupId>      <artifactId>javax.servlet-api</artifactId>      <version>3.1.0</version>      <scope>provided</scope>    </dependency>    <dependency>      <groupId>javax.servlet</groupId>      <artifactId>jstl</artifactId>      <version>1.2</version>    </dependency>    <dependency>      <groupId>javax.servlet.jsp</groupId>      <artifactId>javax.servlet.jsp-api</artifactId>      <version>2.3.1</version>      <scope>provided</scope>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-web</artifactId>      <version>5.3.1</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-context</artifactId>      <version>5.3.1</version>    </dependency> 	<dependency>       <groupId>org.springframework</groupId>       <artifactId>spring-webmvc</artifactId>       <version>5.3.1</version>     </dependency>

Spring整合MVC框架核心思路

  1. 如何准备工厂?

    //使用的是WebXmlApplicationContext而不再是ClassPathApplicationContextApplicationContext applicationContext = new WebXmlApplicationContext("/applicationContext.xml")
  2. 如何保证工厂唯一、共用?
    共用:把ApplicationContext存放在ServletContext域中
    唯一:在ServletContext对象创建的同时创建ApplicationContext,因为ServletContext只会创建一次,所以ApplicationContext也就只有一个。使用ServletContextListener,就可以监听ServletContext的创建,把创建工厂的代码放在里面。

Spring已经封装了一个ContextLoaderListener,作用是为我们创建工厂并存放在ServletContext中。

在这里插入图片描述
在这里插入图片描述

ContextLoaderListener的使用方式:

由于他是一个监听器,所以在web.xml里配置即可。同时还要指定配置文件具体存放的位置!

<listener>	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param>	<param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext.xml</param-value></context-param>

在Controller中获取ApplicationContext:

@RequestMapping("/hello")public String hello(HttpServletRequest request){       ServletContext context = request.getServletContext();    ApplicationContext applicationContext = (ApplicationContext) context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);    System.out.println(applicationContext);    return "success";}
上一篇:js中使用jQuery读/写cookie的值
下一篇:数据结构实验四 查找和排序算法实现

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月01日 14时27分34秒