SpringMVC数据传递及乱码问题

基础环境搭建请参考SringMVC入门程序

一、SpringMVC数据处理

1:resful 路径传值

http://localhost/get/1/2

/*  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数据传递及乱码问题

SpringMVC数据传递及乱码问题

上一篇:Attr.checkId()方法


下一篇:Eclipse用法和技巧二十五:eclipse图标的含义