struts2前端传值到后端出现中文乱码的解决办法

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

1、自定义编码器转码(据说很不推荐这种方式)

    (1)解码器

package com.jack.utils;

import java.io.UnsupportedEncodingException;

import com.jack.model.Academy;

public class ConvertCharacter {
	/**
	 * 手动解码,解决前端传值到后端的中文乱码问题
	 * 
	 * @param s
	 * @return
	 */
	public String Convert(String s) {
		String result = null;
		byte[] temp;
		try {
			temp = s.getBytes("iso-8859-1");
			result = new String(temp, "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
    // 返回已经解码了的对象
	public Object ConvertObj(Object obj) {
		if (obj instanceof Academy) {
			obj = (Academy) obj;
			((Academy) obj).setAcdCode(Convert(((Academy) obj).getAcdCode()));
			((Academy) obj).setAcdName(Convert(((Academy) obj).getAcdName()));
			((Academy) obj).setRemarks(Convert(((Academy) obj).getRemarks()));
		}
		return obj;
	}
}

    (2)当action中执行保存数据到数据库操作时,在action中调用该解码器解码

package com.jack.model;

import java.io.UnsupportedEncodingException;
import java.util.Set;

import lombok.Data;

import com.jack.dao.ManagerImple;
import com.jack.utils.ConvertCharacter;

@Data
public class Academy extends UrlManager {
	private int acdId;
	private String acdName;
	private String acdCode;
	private String remarks;
	private Set stuCls;

	/**
	 * 
	 * 直接将model和action结合,在model中定义增删改查即可
	 */
	private ManagerImple managerIm;

	public boolean save() throws UnsupportedEncodingException {

		managerIm = new ManagerImple();

		ConvertCharacter convert = new ConvertCharacter();

		System.out.println("保存:"+convert.ConvertObj(this));// 中文转码

		boolean isOk = false;

		isOk = managerIm.doSave(this);

		return isOk;
	}
}

2、通过配置过滤器编码方式解决(推荐使用,可我配置了几个小时都没成功!)

转载于:https://my.oschina.net/zhanggongming/blog/675242

你可能感兴趣的:(struts2前端传值到后端出现中文乱码的解决办法)