Form表单乱码
在Web项目中,当前端页面发送表单数据(中文)给Controller时候,处理完之后又发送到前端页面,有时候会产生乱码的情况。
简单粗暴SpringMVC:
在web.xml中配置如下
<!--配置SpringMVC的乱码过滤-->
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这样问题就结束了
如果想自定义解决方法:创建一个过滤器,具体实施
1 前端表单页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>form</title>
</head>
<body>
<form action="/mvc04/e/test01" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
2 Controller处理数据
package com.xzzlx.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class Encoding {
@PostMapping("/e/test01")
public String test01(String name, Model model){
model.addAttribute("msg", name);
return "hello";
}
}
3 返回hello.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
4 发生乱码
此时出现的效果
5 解决
创建一个过滤器的类
package com.xzzlx.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 req,
ServletResponse resp,
FilterChain filterChain)
throws IOException, ServletException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
filterChain.doFilter(req, resp);
}
@Override
public void destroy() {
}
}
在web.xml文件中注册过滤器
注册的时候,filter-mapping中应该为/*
,不能用/
因为我们的页面是JSP,而/
只能扫描所有非JSP文件,/*
则可以过滤包括JSP的所有文件
<?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">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.xzzlx.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
6 运行
测试运行我们的程序即可