2024.3.11 Monday
接上文 【WEEK2】 【DAY5】数据处理及跳转之数据处理【中文版】
目录
- 5.3.乱码问题
- 5.3.1.在首页编写一个提交的表单
- 5.3.2.后台编写对应的处理类
- 5.3.3.修改springmvc-controller.xml
- 5.3.4.运行
- 5.3.5.解决乱码
- 5.3.5.1.Servlet(无法解决)
- 5.3.5.2.使用过滤器
- 1. 自定义filter
- 2. 修改web.xml(添加以下代码)
- 3. 直接使用官方提供的过滤器
- 5.3.5.3.乱码的总结部分
5.3.乱码问题
5.3.1.在首页编写一个提交的表单
在web->新建form.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>FromEncodingController</title>
</head>
<body>
<%--以post方式提交--%>
<form action="/springmvc_04_controller_war_exploded/EC/t1" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
5.3.2.后台编写对应的处理类
Controller->新建EncodingController.java
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class EncodingController {
@PostMapping("/EC/t1")
public String test1(String name, Model model){
System.out.println(name);
model.addAttribute("msg",name);
//这里name千万不能用双引号,否则页面传入的字符永远是name而非用户输入的内容
return "test";
}
}
5.3.3.修改springmvc-controller.xml
取消注释
5.3.4.运行
http://localhost:8080/springmvc_04_controller_war_exploded/form.jsp
点击提交后产生乱码
http://localhost:8080/springmvc_04_controller_war_exploded/EC/t1
5.3.5.解决乱码
5.3.5.1.Servlet(无法解决)
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
@Controller
public class EncodingController {
@PostMapping("/EC/t1")
public String test1(String name, Model model, HttpServletRequest request)throws UnsupportedEncodingException {
request.setCharacterEncoding("utf-8"); //此方法无用->用过滤器解决乱码
System.out.println(name);
model.addAttribute("msg",name);
//这里name千万不能用双引号,否则页面传入的字符永远是name而非用户输入的内容
return "test";
}
}
5.3.5.2.使用过滤器
1. 自定义filter
- 新建EncodingFilter.java
选择javax.servlet类型的Filter导入
package com.kuang.filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest,servletResponse);
//写完过滤器去配置文件web.xml注册
}
@Override
public void destroy() {
}
}
2. 修改web.xml(添加以下代码)
<!-- filter -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.kuang.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 或直接使用已有的非官方过滤器(效果最强)
package com.kuang.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;
/**
* 解决get和post请求 全部乱码的过滤器
*/
public class GenericEncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
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);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
//自定义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;
}
}
3. 直接使用官方提供的过滤器
- 仅修改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">
<!--1.配置DispatcherServlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 配置文件的位置,是在resource文件夹下的文件名 -->
<param-value>classpath:springmvc-controller.xml</param-value>
<!-- 这里仍然需要配置springmvc-controller.xml文件 -->
</init-param>
<!-- 启动顺序,数字越小,启动越早 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--所有请求都会被springmvc拦截 -->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- filter -->
<filter>
<filter-name>encoding</filter-name>
<!-- <filter-class>com.kuang.filter.EncodingFilter</filter-class> <!–一般情况下不使用自己书写的过滤器(本行)–>-->
<!--使用官方的即可(把自定义的第32行改成如下34~38行)-->
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</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>
</web-app>
- 运行
http://localhost:8080/springmvc_04_controller_war_exploded/form.jsp
点击提交后会产生乱码的问题被解决:
http://localhost:8080/springmvc_04_controller_war_exploded/EC/t1
5.3.5.3.乱码的总结部分
- 一般情况下,SpringMVC默认的乱码处理就已经能够很好的解决了
- 然后在web.xml中配置这个过滤器即可(无论是自定义的还是官方的都需要配置)
- 乱码问题,需要平时多注意,在尽可能能设置编码的地方,都设置为统一编码 UTF-8