1. 首页
  2. 软件开发
  3. SpringMVC通过ModelAndView、Model、map、ModelMap向request域共享数据的原理和用法。

SpringMVC通过ModelAndView、Model、map、ModelMap向request域共享数据的原理和用法。

  • 发布于 2024-08-17
  • 0 次阅读

在Spring MVC中,可以使用ModelAndView、Model、Map和ModelMap等方式来向request域共享数据,以便在视图中显示这些数据。这些方法的原理都是通过将数据存储在request域中,使得在整个请求生命周期内都可以访问这些数据。

  1. ModelAndView
    包含了视图名称和模型数据。模型数据通过addObject方法添加到ModelAndView中。

代码如下:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MyController {
   

    @GetMapping("/hello")
    public ModelAndView hello() {
   
        ModelAndView modelAndView = new ModelAndView("helloView");
        modelAndView.addObject("message", "Hello, World!");
        return modelAndView;
    }
}
  1. Model
    一个接口,通过addAttribute方法向模型中添加属性。

代码如下:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {
   

    @GetMapping("/hello")
    public String hello(Model model) {
   
        model.addAttribute("message", "Hello, World!");
        return "helloView";
    }
}
  1. Map
    通过Map类型的参数,可以向模型中添加属性。

代码如下:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Map;

@Controller
public class MyController {
   

    @GetMapping("/hello")
    public String hello(Map<String, Object> model) {
   
        model.put("message", "Hello, World!");
        return "helloView";
    }
}
  1. ModelMap
    它是Model接口的实现类,也可以用来向模型中添加属性。

代码如下:

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {
   

    @GetMapping("/hello")
    public String hello(ModelMap model) {
   
        model.addAttribute("message", "Hello, World!");
        return "helloView";
    }
}

原文链接: https://blog.csdn.net/2401_82884096/article/details/137963162