java web后台传参到前台中文乱码问题的解决

一、通过设置response编码解决

response.setCharacterEncoding("utf-8");

二、设置requestMapping的product属性解决

@RequestMapping(value = "/login.do",produces = "text/plain;charset=utf-8")



下面附上这里的具体案例:

@RequestMapping(value = "/login.do",produces = "text/plain;charset=utf-8")
    public String login(String username, String password, HttpServletRequest request, HttpServletResponse response){

        response.setCharacterEncoding("utf-8");

        List users =  userService.selectByUsername(username);

        ImgFormat message = new ImgFormat();

        // 通过用户名来匹配登录的用户信息
        for(User u : users){
            if(u.getUsername().equals(username)){
                if(u.getPassword().equals(password)){

                    // 将用户信息保存到session中
                    HttpSession session = request.getSession();
                    session.setAttribute("user",u);

                    // 返回一个json格式的数据
                    message.setCode(1);
                    message.setMsg("登陆成功");
                    message.setData(JSONObject.fromObject(u));
                    return JSONObject.fromObject(message).toString();
                }
                message.setCode(0);
                message.setMsg("密码不正确");
                return JSONObject.fromObject(message).toString();
            }
            message.setCode(0);
            message.setMsg("账号不存在");
            return JSONObject.fromObject(message).toString();
        }
        message.setCode(0);
        message.setMsg("请登录账户");
        return JSONObject.fromObject(message).toString();
    }

参考文献:Fantasy_99 SSM框架:解决后台传数据到前台中文乱码问题,使用@ResponseBody返回json 中文乱码

你可能感兴趣的:(坑)