@ResponseBody

来源:互联网 发布:nba01年总决赛数据 编辑:程序博客网 时间:2024/05/29 14:13
环境: jdk1.7
    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-webmvc</artifactId>      <version>4.3.4.RELEASE</version>    </dependency>
SpringMvc只所以简单是用<mvc:annotation-driven/>一行代码启动了所有注解的默认配置

返回视图的写法
    @GetMapping("view1")    public ModelAndView view1(ModelAndView mav) {        mav.setViewName("view1");        return mav;    }    @GetMapping("view2")    public String view2() {        return "view2";    }

若要直接往response中写内容而不经过视图解析器时可以使用@ResponseBody
    @GetMapping("json1")    @ResponseBody    public Object view() {        Map<String, String> map = new HashMap<String, String>();        map.put("a", "a");        return map;    }

要想responseBody返回Json,必须要加入json解析的jar包
    <dependency>      <groupId>com.fasterxml.jackson.core</groupId>      <artifactId>jackson-databind</artifactId>      <version>2.8.7</version>    </dependency>

加入以上jar包后可以返回json了
responseBody返回的内容不止json一种,还有text,xml和其他,如何控制返回的类型由程序自动选择,
可以查找springmvc的HttpMessageConverter部分内容
一次请求的内容如下
request-headers"Content-Type":"application/x-www-form-urlencoded" --告诉程序请求的类型为表单"Accept":"application/json;charset=UTF-8" -- 告诉程序接收的类型为json,字符编码为utf-8

    // 这里的produces = "text/html;charset=UTF-8" 个人理解为 request-hearder中的Accpet,不写默认的编码为ISO-8859-1中文乱码,在返回为json时默认为application/json;charset=UTF-8    @GetMapping(value = "text1", produces = "text/html;charset=UTF-8")    @ResponseBody    public String text1() {        return "你好";    }

    /**     * 返回json时可以格式化,还有很多其他json注解     */    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")    private Date createTime;

Content-Type和Accept详解get请求:request headers : 不存在 Content-Type, 存在 Accept(值为mediaType:text/html,application/json,...)response headers : 存在 Content-Type(值为request headers中Accept的值,表示告诉浏览器当前body中内容的类型), 不存在 Acceptpost请求:request headers: 存在 Content-Type (知道的有application/x-www-form-urlencoded[表单], form-data[文件上传],其它未知),存在 Accept(和get的值一样)response headers : 存在 Content-Type(值为request headers中Accept的值,表示告诉浏览器当前body中内容的类型), 不存在 Accept


0 0
原创粉丝点击