SpringMVC框架理解1

简介: SpringMVC框架理解

1. Spring与Web环境集成


1.1 ApplicationContext应用上下文获取方式


应用上下文对象是通过new ClasspathXmlApplicationContext(spring配置文件) 方式获取的,但是每次从容器中获得Bean时都要编写new ClasspathXmlApplicationContext(spring配置文件) ,这样的弊端是配置文件加载多次,应用上下文对象创建多次。


在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象了。


1.2 手写案例


① 创建监听


package com.terence.listener;
import com.terence.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoaderListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        //读取web.xml中的全局参数
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
        //将Spring的应用上下文对象存储到ServletContext域中
        servletContext.setAttribute("app",app);
        System.out.println("spring容器创建完毕....");
    }
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}


② 创建获取pplicationContext对象的工具类


package com.terence.listener;
import org.springframework.context.ApplicationContext;
import javax.servlet.ServletContext;
public class WebApplicationContextUtils {
    public static ApplicationContext getWebApplicationContext(ServletContext servletContext){
        return (ApplicationContext) servletContext.getAttribute("app");
    }
}


③ 创建servlet的测试类


package com.terence.web;
import com.terence.listener.WebApplicationContextUtils;
import com.terence.service.UserService;
import org.springframework.context.ApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        //ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        UserService userService = app.getBean(UserService.class);
        userService.save();
    }
}


 ④ 配置webapp/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--全局初始化参数-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!--配置监听器-->
    <listener>
        <listener-class>com.terence.listener.ContextLoaderListener</listener-class>
    </listener>
    <!--配置测试用的servlet-->
    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.terence.web.UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/userServlet</url-pattern>
    </servlet-mapping>
</web-app>


⑤测试

浏览器访问

http://localhost:8080/spring_mvc/userServlet


控制台成功输出

39.png


1.3 Spring提供获取应用上下文的工具


上面的手写案例只是为了方便大家理解,Spring提供了一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。


所以我们需要做的只有两件事:


①在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)


②使用WebApplicationContextUtils获得应用上下文对象ApplicationContext


1.3.1 导入Spring集成web的坐标

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>


1.3.2 配置ContextLoaderListener监听器


<!--全局初始化参数-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--Spring的监听器-->
<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>


1.3.3 使用WebApplicationContextUtils获得应用上下文对象

ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);


2. SpringMVC的简介


2.1 SpringMVC概述


SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于SpringFrameWork 的后续产品,已经融合在 Spring Web Flow 中。


SpringMVC 已经成为目前最主流的MVC框架之一,并且随着Spring3.0 的发布,全面超越 Struts2,成为最优秀的 MVC 框架。它通过一套注解,让一个简单的 Java 类成为处理请求的控制器,而无须实现任何接口。同时它还支持 RESTful 编程风格的请求。


2.2 SpringMVC快速入门


需求:客户端发起请求,服务器端接收请求,执行逻辑并进行视图跳转。


40.png


开发步骤实现

①导入SpringMVC相关坐标


<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
<!--SpringMVC坐标-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.0.5.RELEASE</version>
</dependency>
<!--Servlet坐标-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
<!--Jsp坐标-->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.2.1</version>
    <scope>provided</scope>
</dependency>


②配置SpringMVC核心控制器DispathcerServlet


<servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>


③创建Controller类和

success.jsp 视图页面


public class UserController {
    public String save(){
        System.out.println("Controller save running....");
        return "success.jsp";
    }
}


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Success!</h1>
</body>
</html>


④使用注解配置Controller类中业务方法的映射地址


@Controller
public class UserController {
    // 请求地址  http://localhost:8080/user/quick
    @RequestMapping(value="/quick")
    public String save(){
        System.out.println("Controller save running....");
        return "success.jsp";
    }
}


⑤配置SpringMVC核心文件 spring-mvc.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.alibaba.com/schema/stat"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd">
    <!--Controller的组件扫描-->
    <context:component-scan base-package="com.terence"></context:component-scan>
</beans>


⑥客户端发起请求测试


http://localhost:8080/spring_mvc/quick


控制台打印


41.png


页面显示


42.png


2.3 SpringMVC流程图示

43.png


2.4 知识要点


SpringMVC的开发步骤


①导入SpringMVC相关坐标


②配置SpringMVC核心控制器DispathcerServlet


③创建Controller类和视图页面


④使用注解配置Controller类中业务方法的映射地址


⑤配置SpringMVC核心文件 spring-mvc.xml


⑥客户端发起请求测试


3. SpringMVC的组件解析


3.1 SpringMVC的执行流程


45.png


①用户发送请求至前端控制器DispatcherServlet。


②DispatcherServlet收到请求调用HandlerMapping处理器映射器。


③处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。


④DispatcherServlet调用HandlerAdapter处理器适配器。


⑤HandlerAdapter经过适配调用具体的处理器(Controller,也叫后端控制器)。


⑥Controller执行完成返回ModelAndView。


⑦HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。


⑧DispatcherServlet将ModelAndView传给ViewReslover视图解析器。


⑨ViewReslover解析后返回具体View。


⑩DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)。DispatcherServlet响应用户。


相关文章
|
9月前
|
容器
SpringMVC常见组件之HandlerExceptionResolver分析-2
SpringMVC常见组件之HandlerExceptionResolver分析-2
55 0
|
4月前
|
JSON 前端开发 搜索推荐
SpringMVC框架(2)
SpringMVC框架(2)
36 2
|
4月前
|
JSON Java 数据格式
SpringMVC框架(1)
SpringMVC框架
17 1
|
4月前
|
XML 存储 Java
SpringMVC常见组件之HandlerMapping分析
SpringMVC常见组件之HandlerMapping分析
117 0
|
4月前
|
XML 缓存 前端开发
SpringMVC常见组件之HandlerAdapter分析
SpringMVC常见组件之HandlerAdapter分析
60 0
|
9月前
|
设计模式 前端开发 Java
SpringMVC框架
SpringMVC框架
|
前端开发 Java 定位技术
SpringMVC之ModelAndView类详细分析(全)
目录前言1. 方法2. 配置3. addObject 添加对象详解4. 重定向 前言 通过查看源码可以得知 这个类主要是 在web MVC框架中的模型和视图的Holder。 请注意,这些是完全不同的。 这个类仅仅保存了两者,使得控制器可以在一个返回值中同时返回模型和视图。 表示处理程序返回的模型和视图,由DispatcherServlet解析。 视图可以采用String视图名的形式,需要通过ViewResolver对象解析; 或者,可以直接指定一个View对象。 该模型是一个Map,允许使用多个按名称键控
221 0
SpringMVC之ModelAndView类详细分析(全)
|
设计模式 前端开发 Java
SpringMVC框架(详解)上
SpringMVC框架(详解)
|
JSON 前端开发 Java
SpringMVC框架(详解)下
SpringMVC框架(详解)
|
设计模式 JSON 前端开发
2021-08-11Spring MVC,入门项目搭建及流程,springMVC的适配器和映射器,基于注解的controller,映射请求,方法返回值,requestmapping注解
2021-08-11Spring MVC,入门项目搭建及流程,springMVC的适配器和映射器,基于注解的controller,映射请求,方法返回值,requestmapping注解
53 0