2023-01-20
一、SpringMVC处理响应数据
1、处理响应数据方式一
(1)语法:使用ModelAndView对象作为返回值类型,处理响应数据
(2)底层实现原理
①数据共享到request域
②跳转路径方式:转发
(3)示例代码
@RequestMapping("/testModelAndView") public ModelAndView testModelAndView(){ ModelAndView mv = new ModelAndView(); //设置model mv.addObject("stuName", "zhangsan"); //设置view mv.setViewName("response_success"); return mv; }
<h3>测试Response数据</h3> <a th:href="@{/testModelAndView}">测试testModelAndView数据</a>
2、处理响应数据方式二
(1)语法:使用Map或Model或ModelMap作为参数入参,处理响应数据
(2)底层实现原理
①数据共享到request域
②跳转路径方式:转发
(3)示例代码
private final static String SUCCESSRESPONSE="response_success";
@RequestMapping("/testModelOrMapOrModelMap") public String testModelOrMapOrModelMap(ModelMap modelMap){ modelMap.addAttribute("stuName","lisi"); return SUCCESSRESPONSE; }
3、将数据共享到session域
(1)示例代码
@RequestMapping("/testSession") public String testSession(HttpSession session){ session.setAttribute("stuName","wangwu"); return SUCCESSRESPONSE; }
二、SpringMVC处理请求域响应乱码问题
1、javaWeb解决乱码
(1)解决POST请求乱码
request.setCharacterEncoding("UTF-8");
(2)解决GET请求乱码
<Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1" connectionTime="20000" redirectPort="8443" />
(3)解决响应乱码
response.setCharacterEncoding("GBK"); response.setContentType("text/html;charset=UTF-8");
2、使用CharacterEncodingFilter步骤
(1)注意:CharacterEncodingFilter必须注册在第一个过滤器位置
(2)步骤:
①注册CharacterEncodingFilter
②为CharacterEncodingFilter设置初始化
<!-- 解决中文乱码的过滤器(注意:该过滤器要放在最上面)--> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!-- 设置初始化字符集--> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <!-- 解决请求和响应乱码--> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
标签:处理,SpringMVC,乱码,响应,ModelAndView,CharacterEncodingFilter From: https://www.cnblogs.com/isDaHua/p/17062398.html