后台往前台传值,出现中文乱码问题。

来源:互联网 发布:网络中控品牌 编辑:程序博客网 时间:2024/06/05 19:13

前台代码注意两个地方:

一个是在JSP页面上第一行加代码<%@ page contentType="text/html; charset=UTF-8" language="java" %>,

另外也要在head.jsp中加入<meta charset="utf-8">。

另外看一下自己浏览器的编码是不是选错了,我用firefox选成unicode。


直接上代码:

@ResponseBody@RequestMapping(value="/kjhjdh",produces = {"application/text;charset=UTF-8"})//加此中文乱码解除public String returnAudit(AssignCaseForm assignCaseForm,HttpServletRequest request,HttpServletResponse response) throws IOException{request.setCharacterEncoding("utf-8");  response.setContentType("text/html;charset=utf-8");return "";}

拓展:

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="<span style="font-family: "Courier New", monospace; white-space: pre; background-color: rgb(247, 247, 247);"><strong><span style="color:#ff0000;">MediaType.APPLICATION_JSON_VALUE"+";charset=utf-8</span></strong>"</span>)        @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      }  



原创粉丝点击