• 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  
    }  
    
  • 相关阅读:
    接口与抽象类
    观察者模式
    kibana安装
    使用CGLib完成代理模式遇到的错误
    代理模式
    HashMap resize方法的理解(一)
    装饰模式
    volatile关键字解析(二)
    https网站引用http路径的js和css失效解决办法
    IIS7.5配置自动添加www 及 限制通过IP访问web
  • 原文地址:https://www.cnblogs.com/userzf/p/13824972.html
Copyright © 2020-2023  润新知