controller 返回界面 中文乱码


@ResponseBody
    @RequestMapping(value = "/addStudent",method = RequestMethod.GET)
    public String addStudent(Student student){
        if (ssi.addStudent(student)) {
            return "<script>alert('添加成功');location.href='/sc/list'</script>";
        }
        return "<script>alert('添加失败');location.href='addStudent'</script>";
    }

运行结果

解决方式 加上 produces 属性

@ResponseBody
    @RequestMapping(value = "/addStudent",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
    public String addStudent(Student student){
        if (ssi.addStudent(student)) {
            return "<script>alert('添加成功');location.href='/sc/list'</script>";
        }
        return "<script>alert('添加失败');location.href='addStudent'</script>";
    }

produces可能不算一个注解,因为什么呢,它是注解@requestMapping注解里面的属性项,

它的作用是指定返回值类型,不但可以设置返回值类型还可以设定返回值的字符编码;

还有一个属性与其对应,就是consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

他们的使用方法如下:

一、produces的例子

produces第一种使用,返回json数据,下边的代码可以省略produces属性,因为我们已经使用了注解@responseBody就是返回值是json数据:

@Controller  
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")  
@ResponseBody  
public Pet getPet(@PathVariable String petId, Model model) {     
    // implementation omitted  
}  

produces第二种使用,返回json数据的字符编码为utf-8.:

@Controller  
@RequestMapping(value = "/pets/{petId}", produces="MediaType.APPLICATION_JSON_VALUE"+";charset=utf-8")  
@ResponseBody  
public Pet getPet(@PathVariable String petId, Model model) {      
    // implementation omitted  
}  

二、consumes的例子( 方法仅处理request Content-Type为“application/json”类型的请求。)

@Controller  
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")  
public void addPet(@RequestBody Pet pet, Model model) {      
    // implementation omitted  
}  
posted @   张什么锋  阅读(1469)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
历史上的今天:
2019-10-16 谷歌浏览器直接启动打印不预览解决方案
点击右上角即可分享
微信分享提示