首页 > 其他分享 >spring boot——请求与参数校验——spring-mvc-域对象共享数据——介绍二

spring boot——请求与参数校验——spring-mvc-域对象共享数据——介绍二

时间:2023-01-15 21:02:30浏览次数:37  
标签:spring org boot request mvc ModelAndView import 共享 Model

 

 

 

 

 

 

 

 

package org.example.controller.requestparam;

import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class ShareValueController002 {

    /**
     *
     *
     *可以通过 Spring 提供的 ModelAndView 向 reuqest 域对象中共享数据。ModelAndView 主要由 model(模型)和 view(视图)两部分组成。其中,model 负责数据共享,而 view 则主要用于设置视图,实现页面的跳转。
     *
     * 在 Controller 类中,ModelAndView 只有在作为控制器方法的返回值,返回给前端控制器(DispatcherServlet)时,前端控制器解析才会去解析它,示例代码如下。
     *
     * @return
     */


    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        /**
         * ModelAndView有Model和View的功能
         * Model主要用于向请求域共享数据
         * View主要用于设置视图,实现页面跳转
         */
        ModelAndView mav = new ModelAndView();
        //向请求域共享数据
        mav.addObject("testScope", "hello,ModelAndView");
        //设置视图,实现页面跳转
        mav.setViewName("success");
        return mav;
    }




    /**
     *
     *
     *
     *使用 Model 向 request 域对象中共享数据
     *我们可以在 Controller 控制器方法中设置一个 Model 类型的形参。通过它,我们也可以向 request 域对象中共享数据,示例代码如下。
     *
     */

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






    /**
     *
     * 使用 Map 向 request 域对象中共享数据
     * 我们可以在 Controller 控制器方法中设置一个 Map 类型的形参。通过它,我们也可以向 request 域对象中共享数据,示例代码如下。
     *
     */

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






    /**
     *
     * 使用 ModelMap 向 request 对象中共享数据
     * 我们可以在 Controller 控制器方法中设置一个 ModelMap 类型的形参。通过它,我们也可以向 request 域对象中共享数据,示例代码如下。
     *
     */
    @RequestMapping("/testModelMap")
    public String testModelMap(ModelMap modelMap) {
        modelMap.addAttribute("testScope", "hello,ModelMap");
        return "success";
    }




}

 

标签:spring,org,boot,request,mvc,ModelAndView,import,共享,Model
From: https://www.cnblogs.com/xiaobaibailongma/p/17054100.html

相关文章