SpringMvc学习笔记(八)服务端数据传递客户端显示-后台传数据到前台

xiaoxiao2021-03-01  25

JavaWeb阶段传递数据,ModelAndView传递数据,其他方式传递数据,通过读取ModelAndView的源码分析,ResponseEntiy返回JSON数据 - IE和谷歌浏览器正常,JSON返回日期处理方式

源码获取github

1.项目结构

2.JavaWeb阶段传递数据

ModelAndViewDemoController.java

/** * JavaWeb阶段传递数据 * * @param request * @param response * @throws ServletException * @throws IOException */ @GetMapping("/server01") @ResponseBody //不处理 public void test01(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("hs", "和尚"); request.setAttribute("class", "计算机"); request.setAttribute("number", 8); //请求转发传递数据---这个没有通过视图解析器 request.getRequestDispatcher("/WEB-INF/jsp/result01.jsp").forward(request, response); }

result01.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h2>数据获取方式</h2> <h2>${requestScope.hs}</h2> <h2>${requestScope["class"]}</h2> <h2>${number} ---默认情况下是从pageContext->request->session->application下开始寻找</h2> </body> </html>

3.ModelAndView传递数据—指明了key值

ModelAndViewDemoController.java

/** * 通过ModelAndView传递数据 * * @return */ @GetMapping("/server02") public ModelAndView test02() { ModelAndView mav = new ModelAndView(); // mav.addObject() 没有指明KEY //一步一步的追源码,发现一个ModelMap的类实例化对象.用它的addAttribute方法添加,ModelMap又是继承了HashMap mav.addObject("title", "通过ModelAndView传递数据"); mav.addObject("hs", "中国和尚"); mav.addObject("class", "计算机计科"); mav.addObject("number", 11); mav.setViewName("jsp/result02"); //请求转发,通过视图解析器 return mav; }

result02.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h2>${title}</h2> <h2>${requestScope.hs} --指明范围了的</h2> <h2>${requestScope["class"]}</h2> <h2>${number} ---默认情况下是从pageContext->request->session->application下开始寻找</h2> </body> </html>

4.ModelAndView传递数据—没有指明key值

ModelAndViewDemoController.java

/** * 传递数据没有指明KEY_默认KEY的规则 * * @return */ @GetMapping("/server03") public ModelAndView test03() { ModelAndView mav = new ModelAndView(); mav.addObject("integer", 100); mav.addObject(200); mav.addObject("string", "字符串"); mav.addObject("悟空"); // 规则:客户端获取没有加key的数据,默认key正常是数据对应的类型的首字母小写 Integer---integer String---string // 两个key一样的,只认最后一个 // double是关键字,不能${double},只能${requestScope["double"] } double a = 123.123; mav.addObject(a); User user = new User(); user.setMydate(new Date()); mav.addObject(user); mav.setViewName("jsp/result03"); //请求转发,通过视图解析器 return mav; }

result03.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt" %> <html> <head> <title>Title</title> </head> <body> <h2>${requestScope.integer }</h2> <h2>${requestScope.string }</h2> <h2>${requestScope["double"] }-----因为double是关键字,所以不能.double</h2> <h2>${requestScope.user.mydate }</h2> <h2>${requestScope["user"]["mydate"] }</h2> 日期格式化 <fmt:formatDate value="${user.mydate }" pattern="yyyy-MM-dd HH:mm:ss"/> </body> </html>

5.其他方式传递数据,通过读取ModelAndView的源码分析

OtherDemoController.java

package com.hs.web; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import java.util.Map; /** * 其他的方式传递数据 */ @Controller public class OtherDemoController { /** *其他1--通过Map在形参中实例化 * @param map * @return */ @GetMapping("/server04") public String test01(Map<String,Object> map) { map.put("title", "Map在形参中定义,可以传递数据"); map.put("hs", "123"); map.put("class", "12222"); map.put("number", 1111); return "jsp/result04"; //通过请求转发视图解析器 } /** * 其他2--通过ModelMap在形参中实例化 * @param modelMap * @return */ @GetMapping("/server05") public String test02(ModelMap modelMap) { modelMap.addAttribute("title", "ModelMap进行传递数据"); modelMap.addAttribute("hs", "123"); modelMap.addAttribute("class", "12222"); modelMap.addAttribute("number", 1111); return "jsp/result04"; //通过请求转发视图解析器 } /** * 其他3--通过Model接口传递数据 * @param model * @return */ @GetMapping("/server06") public String test03(Model model) { model.addAttribute("title", "Model接口进行传递数据"); model.addAttribute("hs", "123"); model.addAttribute("class", "12222"); model.addAttribute("number", 1111); return "jsp/result04"; //通过请求转发视图解析器 } }

result04.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h2>${title}</h2> <h2>${requestScope.hs} --指明范围了的</h2> <h2>${requestScope["class"]}</h2> <h2>${number} ---默认情况下是从pageContext->request->session->application下开始寻找</h2> </body> </html>

6.ResponseEntiy返回JSON数据 - IE和谷歌浏览器正常

JsonDemoController.java

/** * JSON格式1:ResponseEntity返回JSON数据格式 * * @return */ @GetMapping("/json01") public ResponseEntity<Map<String, Object>> test01() { Map<String, Object> map = new HashMap<>(); map.put("name", "马老板"); map.put("sex", "男"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_HTML); //设置响应方式,在HTML页面上显示 return new ResponseEntity<Map<String, Object>>(map, headers, HttpStatus.CREATED); } /** * JSON格式1:用List存多条JSON数据 * * @return */ @GetMapping("/json02") public ResponseEntity<List<Map<String, Object>>> test02() { List<Map<String,Object>> tempList = new ArrayList<Map<String,Object>>(); Map<String,Object> map = new HashMap<String, Object>(); map.put("name", "马老板"); map.put("sex", "男"); tempList.add(map); map = new HashMap<String, Object>(); map.put("name", "悟空"); map.put("sex", "男"); tempList.add(map); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_HTML); return new ResponseEntity<List<Map<String, Object>>>(tempList, headers, HttpStatus.CREATED); }

7.@ResponseBody推荐方式返回json数据

JsonDemoController.java

/** * JSON格式3:简写方式 * * @return */ @GetMapping("/json03") @ResponseBody //把java数据转换为JSON的字符串 存在BUG(IE浏览器不好使,解决办法在springmvc.xml配置) public Map<String, Object> test03() { Map<String, Object> map = new HashMap<>(); map.put("name", "马老板"); map.put("sex", "男"); return map; } /** * JSON格式4:简写方式 * * @return */ @GetMapping("/json04") public @ResponseBody List<Map<String, Object>> test04() { List<Map<String,Object>> tempList = new ArrayList<Map<String,Object>>(); Map<String,Object> map = new HashMap<String, Object>(); map.put("name", "马老板"); map.put("sex", "男"); tempList.add(map); map = new HashMap<String, Object>(); map.put("name", "悟空"); map.put("sex", "男"); tempList.add(map); return tempList; }

解决BUG问题在springmvc.xml配置

<!--1.启动SpringMVC注解--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!--解决@ResponseBody在IE浏览器的BUG问题--> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="prettyPrint" value="true"/> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/plan;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters>

8.JSON返回日期处理方式

JsonDemoController.java

/** * 处理日期格式,需要在user的date属性下加注解,或者springmvc配置全局日期处理 * @return */ @GetMapping("/json05") @ResponseBody public User test05() { User user = new User(); user.setMydate(new Date()); return user; }

User.java下设置

package com.hs.model; import java.util.Date; public class User { // 相放哪里就放哪里,pattern:格式,timezone:时区,这是设置东八区 // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date mydate; // @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") // @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8") public Date getMydate() { return mydate; } public void setMydate(Date mydate) { this.mydate = mydate; } @Override public String toString() { return "User{" + "mydate=" + mydate + '}'; } }

springmvc.xml中配置全局的

<!--1.启动SpringMVC注解--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <!--解决@ResponseBody在IE浏览器的BUG问题--> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="prettyPrint" value="true"/> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/plan;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <!--解决Jackson转换的日期问题,一劳永逸的办法,全局设置,但是和持久化类中的注解比,谁近更选择谁--> <property name="objectMapper"> <!--property:xxx属性--> <bean class="com.fasterxml.jackson.databind.ObjectMapper"> <!--bean:xx实例化了--> <property name="dateFormat"> <bean class="java.text.SimpleDateFormat"> <!--yyyy-MM-dd HH:mm:ss只能这么写,如果不显示小时,就需要在持久化类中注解设置--> <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/> <!--constructor-arg:xx构造函数--> </bean> </property> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
转载请注明原文地址: https://www.6miu.com/read-4050134.html

最新回复(0)