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