SpringMVC数据传递及乱码问题
基础环境搭建请参考SringMVC入门程序
一、SpringMVC数据处理
1:resful 路径传值
/* http://localhost/get/1/2 */
/*路径传值 必须要用@PathVariable*/
@GetMapping("/get/{id1}/{id2}")
public String getValue(@PathVariable String id1, @PathVariable String id2, Model model){
String msg = id1 + id2;
model.addAttribute("msg",msg);
return "hello";
}
2:参数传值:参数名一致
http://localhost/get2?id=applesnt
@GetMapping("/get2")
public String getValue2(String id,Model model){
model.addAttribute("msg",id);
return "hello";
}
3:参数传值:参数名不一致
http://localhost/get3?username=134
@GetMapping("/get3")
public String getValue3(@RequestParam("username") String name, Model model){
model.addAttribute("msg",name);
return "hello";
}
4:对象传值:UserVo
http://localhost/get4?id=111&name=zhangsan&age=12
@GetMapping("/get4")
public String getValue4(UserVo userVo, Model model){
model.addAttribute("msg",userVo.toString());
return "hello";
}
二、SpringMVC乱码处理
1:编写filter乱码过滤器
com\applesnt\filter\GenericEncodingFilter.java
package com.applesnt.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class GenericEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//处理response的字符编码
HttpServletResponse myResponse=(HttpServletResponse) response;
myResponse.setContentType("text/html;charset=UTF-8");
// 转型为与协议相关对象
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 对request包装增强
HttpServletRequest myrequest = new MyRequest(httpServletRequest);
chain.doFilter(myrequest, response);
}
public void destroy() {
}
//自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
//是否编码的标记
private boolean hasEncode;
//定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
public MyRequest(HttpServletRequest request) {
super(request);// super必须写
this.request = request;
}
// 对需要增强方法 进行覆盖
@Override
public Map getParameterMap() {
// 先获得请求方式
String method = request.getMethod();
if (method.equalsIgnoreCase("post")) {
// post请求
try {
// 处理post乱码
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (method.equalsIgnoreCase("get")) {
// get请求
Map<String, String[]> parameterMap = request.getParameterMap();
if (!hasEncode) { // 确保get手动编码逻辑只运行一次
for (String parameterName : parameterMap.keySet()) {
String[] values = parameterMap.get(parameterName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
try {
// 处理get乱码
values[i] = new String(values[i]
.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
hasEncode = true;
}
return parameterMap;
}
return super.getParameterMap();
}
//取一个值
@Override
public String getParameter(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
if (values == null) {
return null;
}
return values[0]; // 取回参数的第一个值
}
//取所有值
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}
}
2:配置web.xml 注册filter
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--注册乱码过滤器-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.applesnt.filter.GenericEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--1.注册DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/ 匹配所有的请求;(不包括.jsp)-->
<!--/* 匹配所有的请求;(包括.jsp)-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3:springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.applesnt.controller"/>
<!-- 让Spring MVC不处理静态资源 -->
<mvc:default-servlet-handler />
<!--annotation-driven配置帮助我们完成处理器映射器和处理器适配器-->
<mvc:annotation-driven />
<!--视图解析器:DispatcherServlet给他的ModelAndView-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
4:编写form表单提交测试乱码
web\form.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/getform" method="post">
<input type="text" name="name">
<input type="submit" value="乱码测试">
</form>
</body>
</html>
5:编写controller返回的视图页面
web\WEB-INF\jsp\hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
6:编写controller
com\applesnt\controller\HelloController3.java
package com.applesnt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class HelloController3 {
@PostMapping("/getform")
public String getForm(String name,Model model){
model.addAttribute("msg",name);
return "hello";
}
}
7:测试


SpringMVC数据传递及乱码问题的更多相关文章
- 《Java从入门到放弃》入门篇:springMVC数据传递
springMVC中的数据传递方式与JSP和Struts2相比,更加的简单.具体有什么样的区别呢?我们通过下面这张图来对比就知道了. 随手画的,有些错别字,不用太在意..... 接下来,进入正题,sp ...
- SpringMVC保存数据到mysql乱码问题
SpringMVC保存数据到mysql乱码问题 乱码问题常见配置 一.web.xml配置过滤器 <filter> <filter-name>encoding-filter< ...
- SpringMVC -- 梗概--源码--壹--数据传递
附:实体类 Class : User package com.c61.entity; import java.text.SimpleDateFormat; import java.util.Date; ...
- Java 前台后台数据传递、中文乱码解决方法
1.向前台传递数据;2.向后台传递数据;3.ajax post 提交数据到服务端时中文乱码解决方法;4.数组类型参数传递; 1.向前台传递数据:1.1 字符串数据传递: 这种方式只是单一的向前台传递 ...
- SpringMVC之数据传递一
之前的博客中也说了,mvc中数据传递是最主要的一部分,从url到Controller.从view到Controller.Controller到view以及Controller之间的数据传递.今天主要学 ...
- springMVC:将controller中数据传递到jsp页面
1> 将方法的返回值该为ModelAndView在返回时,将数据存储在ModelAndView对象中如: newModelAndView("/WEBINF/jsp/showData.j ...
- 《Java从入门到放弃》入门篇:springMVC数据校验
昨天我们扯完了数据传递,今天我们来聊聊数据校验的问题.来,跟着我一起读:计一噢叫,一按艳. 在springMVC中校验数据也非常简单,spring3.0拥有自己独立的数据校验框架,同时支持JSR303 ...
- Jmeter接口测试实战-数据传递
Jmeter接口测试实战-数据传递 接口与接口之间没有关联的测试是缺乏意义和没有灵魂的,只有数据在不同接口之间传递才能勾画出业务场景重要的链路. 我们用较为通用的http/https协议,接口普遍返回 ...
- 《SpringMVC从入门到放肆》十三、SpringMVC数据校验
上一章,我们学习了SpringMVC的自定义类型转换器,但是如果转换后的数据传递到Controller的方法中,忽然发现有某些属性为Null了,这怎么办?我们需要一种有效的数据校验机制,来对数据进行有 ...
随机推荐
- HDU 3303 Harmony Forever 前缀和+树状数组||线段树
Problem Description We believe that every inhabitant of this universe eventually will find a way to ...
- OpenCV-Python 傅里叶变换 | 三十
目标 在本节中,我们将学习 使用OpenCV查找图像的傅立叶变换 利用Numpy中可用的FFT函数 傅立叶变换的某些应用程序 我们将看到以下函数:cv.dft(),cv.idft()等 理论 傅立叶变 ...
- PyTorch ImageNet 基于预训练六大常用图片分类模型的实战
微调 Torchvision 模型 在本教程中,我们将深入探讨如何对 torchvision 模型进行微调和特征提取,所有这些模型都已经预先在1000类的Imagenet数据集上训练完成.本教程将深入 ...
- 双剑合璧的开源项目Kitty-Cloud
项目地址 https://github.com/yinjihuan/kitty-cloud 背景 做这个项目主要是想将个人的一些经验通过开源的形式进行输出,不一定能帮到所有人,有感兴趣的朋友可以关注学 ...
- 事务框架之声明事务(自动开启,自动提交,自动回滚)Spring AOP 封装
利用Spring AOP 封装事务类,自己的在方法前begin 事务,完成后提交事务,有异常回滚事务 比起之前的编程式事务,AOP将事务的开启与提交写在了环绕通知里面,回滚写在异常通知里面,找到指定的 ...
- Java 类加载器解析及常见类加载问题
Java 类加载器解析及常见类加载问题 java.lang.ClassLoader 每个类加载器本身也是个对象--一个继承 java.lang.ClassLoader 的实例.每个类被其中一个实例加载 ...
- IE,Google Chrome等浏览器,调试模式在控制台可以手动调用页面的方法来调试
IE,Google Chrome等浏览器,调试模式在控制台可以手动调用页面的方法来调试,这种方式也可以进断点.
- vi文本编辑器的学习
vi文本编辑器的启动与退出 启动:快捷键Ctrl+Alt+t进入终端, 在系统提示符($或#)的提示下,输入vi <文件名称>,可以自动载入你要编辑的文件或者新建一个文件. 退出:在指令模 ...
- python--算法相关
一.时间复杂度排序 1.O(1) < O(logn) < O(n) < O(nlogn) < O(n^2) < O(n^3) < O(2^n) < O(n!) ...
- django发送邮件的坑
django发送邮件的坑 配置django发邮件的时候本地发送时好好的,但是放到阿里云的服务器上却不能发送. 经过一系列的排查后终于发现是阿里云把25端口给封了. 后来改用smtps的方式发送,更改d ...