您的位置:首页 > Web前端 > JavaScript

jsp传数据到后台乱码的处理方法

2015-11-24 10:12 369 查看

数据传递之前,先对中文进行编码,如下红色字体:

function saveCommentTemplate()
{
$.ajax({
cache : false,
type:'get',
dataType:'json',
url:'comment/insert',
contentType:'application/json;charset=UTF-8',
data:{name:encodeURI($("#name").val()),
content:encodeURI($("#content").val())},
success:function(data){
alert("ok")
},
error: function() {
alert("error")
}
});
$("#bottom").hide();
}

等数据传过来时,在对数据进行解码:

@RequestMapping(value = "insert")
@ResponseBody
public void insert(@RequestParam("name") String name,@RequestParam("content")String content) throws UnsupportedEncodingException
{
name=URLDecoder.decode(name,"UTF-8");
content=URLDecoder.decode(content,"UTF-8");
commentTemplateService.saveCommentTemplate(name,content);
}
总结四种方法
1、采用decode()方法 页面:Url: '<%=path%>/sfyh/infodata.jsp?type='+encodeURI(ss)
后台
String result = java.net.URLDecoder.decode(type,"UTF-8")
2、采用设置字符集的方式
request.setCharacterEncoding("utf-8")
3、在页面上定义charset的字符集(最有效 最简单)
<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
4、采用转码的方式
页面‘
Url: '<%=path%>/sfyh/infodata.jsp?type='+encodeURIComponent(ss)
后台
result= new String(request.getParameter("type").getBytes("ISO8859-1"),"UTF-8")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: