SpringMVC学习(五):向request域对象共享数据的五种方法

111 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第10天,点击查看活动详情

什么是域对象?

域对象:一个有作用范围的对象,可以在范围内共享数据 request域:代表一次请求的范围,一次请求访问多个资源,即转发,一般用于请求转发的多个资源中共享数据 方法:

1. void setAttribute(String name,Object obj):存储数据
2. Object getAttitude(String name):通过键获取值
3. void removeAttribute(String name):通过键移除键值对

共享方法:

1、使用原生ServletAPI向request域对象共享数据;

2、使用ModelAndView向request域共享数据;

3、使用Model向request域共享数据;

4、使用map向request域对象共享数据;

5、使用ModelMap向request域对象共享数据。

演示与说明

其实所有的方法,底层都是封装成ModelAndView。

1、原生API不做赘述,如果非要使用,那就是在侮辱SpringMVC了(hhh)

2、使用ModelAndView向request域共享数据;

文档结构:

image.png

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">
 
 
    //配置编码过滤器
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
 
    //配置springMVC的前端控制器DispatcherServlet
    <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:springMVC.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>
    
</web-app>

springMVC.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
 
 
<!--    开启组件扫描-->
    <context:component-scan base-package="demo.controller"></context:component-scan>
 
    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
 
                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>
 
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
 
</beans>

index.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 
    <h1 th:href="@{/index}">首页</h1>
    <a th:href="@{/testModelAndView}">测试ModelAndView</a>
 
</body>
</html>

success.html:

使用${}获取变量的值

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 
    success
    <p th:text="${testRequestScope}"></p>
 
</body>
</html>

需要注意的是:p标签中不能直接将thymeleaf的@{}写在文本里,这样会被当做文本来解析,所以需要写在text属性中,并用th指明是thymeleaf语法

TestController.java:

package demo.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class TestController {
 
    @RequestMapping(value = "/")
    public String index(){
        return "index";
    }
 
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        /**
         * ModelAndView有Model和View的功能
         * Model主要用于向请求域共享数据
         * View主要用于设置视图,实现页面跳转
         */
 
        ModelAndView modelAndView = new ModelAndView();
        //处理模型数据,即向请求域request共享数据
        modelAndView.addObject("testRequestScope","hello");
        //设置视图名称
        modelAndView.setViewName("success");
        return modelAndView;
    }
}

运行一下:

 点击 测试ModelAndView:

获取到了传递过来的值。 

3、使用Model向request域共享数据;

其实Model相当于ModelAndView的一部分功能,就简单地贴个代码,不多介绍了

@RequestMapping("/testModel")
    public String testModel(Model model){
        model.addAttribute("testModel","hello");
        return "success";
    }

测试一下:

 

 

 

 

4、使用map向request域对象共享数据;

        写法跟上面两个基本相同

@RequestMapping(value = "/testMap")
    public String testMap(Map<String,Object>map){
        map.put("testMap","hello");
        return "success";
    }

测试一下:

 

5、使用ModelMap向request域对象共享数据。

@RequestMapping(value = "testModelMap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("testModelMap","hello");
        return "success";
    }

 

除了原生Servlet之外,剩下四种方法任选一种使用就行,当然如果执意要用原生servlet也可以。