spring mvc ajax 中文,springmvc ajax返回数据中文乱码-Fun言

springmvc ajax返回数据中文乱码 问题经常出现,这里提供两种解决办法。

这里是一个 登录的例子,ajax 验证用户名和密码$("#loginForm").submit(function () {

$.ajax({

async: true,

type: "POST",

url: '${pageContext.request.contextPath}/loginVerify',

contentType: "application/x-www-form-urlencoded; charset=utf-8",

data: $("#loginForm").serialize(),

dataType: "json",

success: function (data) {

if(data.code==0) {

alert(data.msg);

} else {

window.location.href="${pageContext.request.contextPath}/admin";

}

},

error: function () {

alert("数据获取失败")

}

})

})

方法一、配置springMVC编码过滤器

这种方法较为常见,在 web.xml顶部添加如下代码CharacterEncodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

forceEncoding

true

CharacterEncodingFilter

/*

注意:最好把这段代码放在web.xml中开头的位置,因为拦截有顺序,如果放在后面的话容易拦截不到。

方法二、@RequestMapping里面加入produces = “text/plain;charset=UTF-8”

@RequestMapping(value = "/loginVerify",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")

@ResponseBody

public String loginVerify(HttpServletRequest request) throws Exception {

Mapmap = new HashMap();

String user = request.getParameter("user");

String password = request.getParameter("password");

UserCustom userCustom = userService.getUserByNameOrEmail(user);

String message="";

if(userCustom==null) {

map.put("code",0);

map.put("msg","用户名无效!");

} else if(!userCustom.getUserPass().equals(password)) {

map.put("code",0);

map.put("msg","密码错误!");

} else {

map.put("code",1);

map.put("msg","");

request.getSession().setAttribute("userId", userCustom.getUserId());

}

String result = new JSONObject(map).toString();

return result;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值