springmvc解决中文乱码

post请求乱码解决

方式一

在web.xml中配置过滤器。声明过滤器时添加初始化参数(常用)

 

方式二

自定义Filter解决post请求中文乱码

1.编写自定义filter类

import javax.servlet.*;
import java.io.IOException;

/**
 * 自定义filter
 */
public class MyCharacterEncodingFilter implements Filter {
   
    private String encoding;
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
    }

    /**
     * doFilter():相当于Servlet的service()
     * @param servletRequest 是HttpServletRequest的父接口
     * @param servletResponse 是HttpServletResponse的父接口
     * @param filterChain 过滤链:
     * 请求会首先进入过滤器。
     * filterChain可以:
     *  1.对请求进行加工
     *  2.决定请求是否可以放行
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.解决中文乱码
        servletRequest.setCharacterEncoding(encoding);
        servletResponse.setContentType("text/html;charset=UTF-8");
        //2.放行请求:写上就是放行(不写就是不放行)
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

2.在web.xml中配置filter

提示:若报红的话可以修改下web.xml头(将下述代码粘上去即可)

<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

 

get请求方式乱码解决

方法一

将参数使用ISO-8859-1编码,再使用utf-8进行解码

//byte[] bytes = motto.getBytes("iso-8859-1");    //使用iso-8859-1编码
//motto = new String(bytes"utf-8");  //使用utf-8解码

//合并了:相当于上面两步骤
motto = new String(motto.getBytes("iso-8859-1"),"utf-8");

方法二

修改tomcat7的默认uri编码为utf-8

Tomcat8之后默认的uri编码就是utf-8,之前的是ISO-8859-1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

healthLau

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值