zoukankan      html  css  js  c++  java
  • 二 @ResponseBody用法

    @ResponseBody底层是通过response.getwriter()方法将数据写回前

    @ResponseBody
    @RequestMapping
    (value="/queryList",method=RequestMethod.POST,produces =
    "application/json; charset=utf-8")//防止乱码
    public String queryList(HttpServletResponse
    response)throws IOException{
    response.setCharacterEncoding("utf-8");
    List list = userService.queryList();
    User user = (User)list.get(0);
    //user.getCreateTime();
    Integer userId = user.getUserId();
    return "查询成功";
    }

    //===================================================
    防止中文乱码
    引起乱码原因为spring mvc使用的默认处理字符串编码为ISO-8859-1
    ,具体参考
    org.springframework.http.converter.StringHttpMessageConver
    ter类中public static final Charset DEFAULT_CHARSET =
    Charset.forName("ISO-8859-1");

    解决方法:
    第一种方法:
    对于需要返回字符串的方法添加注解,如下:
    @RequestMapping(value="/getUsers", produces =
    "application/json; charset=utf-8")
    public String getAllUser() throws
    JsonGenerationException, JsonMappingException, IOException
    {
    List<User> users = userService.getAll();
    ObjectMapper om = new ObjectMapper();
    System.out.println(om.writeValueAsString(users));
    DataGrid dg = new DataGrid();
    dg.setData(users);
    return om.writeValueAsString(dg);
    }
    此方法只针对单个调用方法起作用。
    第二种方法:
    在配置文件中加入
    <mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
    <bean
    class="org.springframework.http.converter.StringHttpMessag
    eConverter">
    <property name="supportedMediaTypes" value =
    "text/plain;charset=UTF-8" />
    </bean>
    </mvc:message-converters>
    </mvc:annotation-driven>

  • 相关阅读:
    写代码的自动提示是怎么出来的...我的WebStorm中不能自动提示Bootstrap中的样式呢
    bootstrap 中是通过写less文件来生成css文件,用什么工具来编写呢?
    flexbox弹性盒模型
    oninput 属性
    操作文件
    深拷贝、浅拷贝、集合
    常用字符串方法
    字典-小练习
    字典
    元组
  • 原文地址:https://www.cnblogs.com/pengmengnan/p/6731776.html
Copyright © 2011-2022 走看看