SpringMVC中如何解决POST请求中文乱码问题GET的又如何处理呢

Scroll Down

SpringMVC中如何解决POST请求中文乱码问题GET的又如何处理呢

method属性值改为post,中文乱码解决:添加springmvc过滤器:org.springframework.web.filter.CharacterEncodingFilter
method属性改为get,中文乱码解决:tomcat的server.xml文件,在Connector标签那一行,添加UriEncoding=UTF-8即可

核心代码show

  • 代码结构图

    image-1660472125352

  • springmvc.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<!-- 配置自动扫描到的包 -->
	<context:component-scan base-package="cn.wangzengqiang.interview.atguigu2019.javaee.spring.springmvc"></context:component-scan>
	
	<!-- 配置视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<!-- 配置不经过处理器方法直接到达响应页面 
		path属性:设置要映射请求地址
		view-name属性:设置视图名
	-->
	<mvc:view-controller path="/testViewResolver" view-name="success"/>
	<!-- 配置了不经过处理器方法直接到达响应页面之后,处理器方法上的@RequestMapping将失效,此时必须配置以下标签 -->
	<mvc:annotation-driven></mvc:annotation-driven>
</beans>

  • web.xml
<?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">
    <!--
    解决post请求的请求乱码问题
    但是不能解决get请求乱码问题:
    1)修改server.xml找到Connector标签,加入URIEncoding="UTF-8"即可
    -->

    <!-- 设置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>
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!-- 注册HiddenHttpMethodFilter,目的是为了将一个POST请求转换为PUT或者DELETE请求 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
  • Employee.java
public class Employee {

	private Integer id;
	private String lastName;
	private String email;
	private Department dept;

	public Employee() {
		super();
	}

	public Employee(Integer id, String lastName, String email, Department dept) {
		super();
		this.id = id;
		this.lastName = lastName;
		this.email = email;
		this.dept = dept;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Department getDept() {
		return dept;
	}

	public void setDept(Department dept) {
		this.dept = dept;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", dept=" + dept + "]";
	}

}
  • Department.java
public class Department {

	private Integer id;
	private String name;

	public Department() {
		super();
	}

	public Department(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Department [id=" + id + ", name=" + name + "]";
	}

}
  • SpringMVCHandler.java
@Controller
public class SpringMVCHandler {

    public static final String SUCCESS = "success";
    public static final String SUCCESS1 = "success1";

    //1.SpringMVC中如何解决POST请求中文乱码问题,GET的又如何处理呢

    /*
     * ★测试入参为POJO
     * Spring MVC会按请求参数名和 POJO属性名进行自动匹配,
     * 		    自动为该对象填充属性值。支持级联属性
     */
    @RequestMapping("/testPOJO")
    public String testPOJO(Employee employee) {
        System.out.println("员工的信息是:" + employee);
        return SUCCESS;
    }



    //1.简单的谈一下SpringMVC的工作流程

    //处理模型数据方式一:将方法的返回值设置为ModelAndView
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
        //1.创建ModelAndView对象
        ModelAndView mav = new ModelAndView();
        //2.设置模型数据,最终会放到request域中
        mav.addObject("user", "admin");
        //3.设置视图
        mav.setViewName("success1");
        return mav;
    }
    /*
     * ★处理模型数据方式二:方法的返回值仍是String类型,在方法的入参中传入Map、Model或者ModelMap
     * 	不管将处理器方法的返回值设置为ModelAndView还是在方法的入参中传入Map、Model或者ModelMap,
     *  SpringMVC都会转换为一个ModelAndView对象
     */
    @RequestMapping("/testMap")
    public String testMap(Map<String , Object> map) {
        //向Map中添加模型数据,最终会自动放到request域中
        map.put("user", new Employee(1, "工一", "gongyi@wangzengqiang.cn", new Department(101, "教学部")));
        return SUCCESS1;
    }
}
  • success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>Success Page</h1>
</body>
</html>
  • index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Insert title here</title>
</head>
<body>
<%--method属性值改为post,中文乱码解决:添加springmvc过滤器:org.springframework.web.filter.CharacterEncodingFilter
method属性改为get,中文乱码解决:tomcat的server.xml文件,在Connector标签那一行,添加UriEncoding=UTF-8即可--%>
<form action="${pageContext.request.contextPath }/testPOJO" method="get">
  <!-- 表单项中的name属性值要与POJO类中的属性名保持一致 -->
  工号:<input type="text" name="id"><br>
  姓名:<input type="text" name="lastName"><br>
  邮箱:<input type="text" name="email"><br>
  部门编号:<input type="text" name="dept.id"><br>
  部门名称:<input type="text" name="dept.name"><br>
  <input type="submit">
</form>
</body>
</html>

彩蛋

  • 1.普通maven工程变为web工程
    项目右键找到add framework suppport,添加web依赖

  • 2.idea 运行tomcat console中文乱码
    idea tomat VM options 设置为 -Dfile.encoding=UTF-8
    idea console乱码:idea.vmoptions文件后面追加:-Dfile.encoding=UTF-8

  • 3.idea 点击无反应
    解决:在idea安装目录下的bin目录下的idea.bat最后添加pause,然后点击idea.bat就可以看到报错信息:
    Error opening zip file or JAR manifest missing
    后来删除C盘IDEA相关文件也不行
    C:\Users\Administrator\AppData\Local\JetBrains\IntelliJIdea2022.2 有日志
    C:\Users\Administrator\AppData\Roaming\JetBrains\IntelliJIdea2022.2 有配置
    后来卸载重装也不行,
    然后用Everything搜索:D:\BaiduNetdiskDownload 发现里面有个文件夹有idea64.exe.vmoptions 文件,以前破解idea时用过
    我在idea中追加:-Dfile.encoding=UTF-8 解决乱码时,打开edit custom vm options中文乱码了,导致启动报错
    总结:
    1.安装文件最后不要放在中文目录下
    2.idea启动不了可以在idea.bat添加pause看异常日志

  • 4.idea maven web out里面无index.jsp
    删除web目录,重新添加web 支持

  • 5.idea运行tomcat console关注的几个文件
    1)server 有乱码
    tomcat安装目录的conf下logging.properties中的java.util.logging.ConsoleHandler.encoding改为UTF-8即可
    2)tomcat catalina log
    3)tomcat localhost log

  • 6.chrome查看源代码