springmvc006-处理模型数据

来源:互联网 发布:win10清理垃圾软件 编辑:程序博客网 时间:2024/06/08 02:50

项目简介:


1,按照项目1的案例搭建一个SpringMVC的框架。(项目一:http://blog.csdn.net/escore/article/details/49490625)

2,我们创建一个新的java类

在类中第一个方法我们直接返回的是ModelAndView,其它三个方法我们是返回字符串,并在方法的入参中分别注入了Map、Model、ModelMap。

也就是说以上四种方式都可以将模型数据传递出去。

只是ModelAndView对象将View(视图)和模型数据(Model)结合在一起返回了,而其他三种则是分开的(四个方法中的“success”相当于视图View)。

通过这四种方式将模型数据传递到了request域中。

注:需要了解的是实际上SpringMVC最后都会将所有的模型数据转换为ModelAndView,不管你是Map、Model等等,或者你没有返回模型数据值返回了“success”(相当于视图)SpringMVC也会将其转换成一个ModelAndView对象,后面将结合视图、视图解析器详细讲解。

import java.util.Map;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@RequestMapping("/testViewAndModel")@Controllerpublic class TestViewAndModel {@RequestMapping("/testModelAndView")public ModelAndView testModelAndView() {ModelAndView mv = new ModelAndView();mv.setViewName("success");String[] names = { "zz", "xx", "cc" };mv.addObject("names", names);return mv;}@RequestMapping("/testMap")public String testMap(Map<String, Object> map) {map.put("name", "maptest");return "success";}@RequestMapping("/testModel")public String testModel(Model model) {model.addAttribute("address", "changsha");return "success";}@RequestMapping("/testModelMap")public String testModelMap(ModelMap modelMap) {modelMap.addAttribute("modelMap", "modelMap");return "success";}}

3,在index.jsp页面中添加如下代码。

<body><a href="testViewAndModel/testModelAndView">testModelAndView</a><br><a href="testViewAndModel/testMap">testMap</a><br><a href="testViewAndModel/testModel">testModel</a><br><a href="testViewAndModel/testModelMap">testModelMap</a><br></body>

4,在views文件中success中添加如下代码。

<body><h1>Success Page</h1><br>names: ${requestScope.names }<br>name : ${requestScope.name }<br>address: ${requestScope.address }<br>address: ${requestScope.modelMap }<br></body>
5,运行流程。

在编写代码后我们通过访问index.jsp页面的地址,然后在通过RequestMapping注解的方法,最后转到success.jsp页面获得我们在后台获得的数据。







0 0
原创粉丝点击