Spring MVC----@ResponseBody注解(json)


1、@ResponseBody注解

該注解會去找HttpMessageConverter<T>,將需要返回的數據轉變成HttpOutputMessage,返回給瀏覽器

 

該注解作用一般可以將數據封裝成json格式的數據返回回去

 

Maven

        <!-- Json Begin -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>
 <!-- Json End -->

 

application配置

<mvc:annotation-driven></mvc:annotation-driven>

如果返回數組報錯,可以配置下面的

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
        </mvc:message-converters>
    </mvc:annotation-driven>

  

其他功能

1、如果不需要某個字段被打包的話

使用@JsonIgnore注解get方法上

前提必須有這個依賴(上面已經有了)

 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
</dependency>

 

2、給json數據(封裝時候)起一個別名

 

 

 

  

2、@RequestBody注解

  將請求的json數據封裝到CmsPage中,如果前端的請求數據中是JSON數據,不是正常的form表單post

  或者我們直接使用add(String a,String b),一個一個接受值

@Override
@PostMapping("/add")
public CmsPageResult add(@RequestBody  CmsPage cmsPage) {
   return pageService.add(cmsPage);
}

將請求的數據轉化成String

controller

    @RequestMapping(value = "/filetest",method = RequestMethod.POST)
    public String filetest(@RequestBody String string){
        try {
            String s2 = new String(string.getBytes("iso-8859-1"), "utf8");
            System.out.println(s2);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "login";
    }

html

<form action="/filetest" method="post" enctype="multipart/form-data">
    <input type="file" name="string">
    <input type="submit" value="提交">
</form>

  

 

 

3、ResponseEntity

文件下載

    @RequestMapping(value = "/filedownload",method = RequestMethod.GET)
    public ResponseEntity filedownload(HttpServletRequest httpServletRequest) throws IOException {
        //設置響應體
        byte[] body = null;
        ServletContext servletContext = httpServletRequest.getSession().getServletContext();
        InputStream resourceAsStream = servletContext.getResourceAsStream("/WEB-INF/abc.txt");
        body = new byte[resourceAsStream.available()];
        resourceAsStream.read(body);
        resourceAsStream.close();

//        方式二,設置響應體
//        System.out.println(httpServletRequest.getSession().getServletContext().getRealPath("/"));
//        String filepath = httpServletRequest.getSession().getServletContext().getRealPath("/")+"WEB-INF\\abc.txt";
//        FileInputStream fileInputStream = new FileInputStream(filepath);
//        body = new byte[fileInputStream.available()];
//        fileInputStream.read(body);
//        fileInputStream.close();

        //設置響應頭
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition","attachment;filename=abc.txt");

        //設置響應碼
        HttpStatus httpStatus = HttpStatus.OK;
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(body,httpHeaders,httpStatus);

        return responseEntity;
    }

 

@JsonFormat與@DateTimeFormat注解的使用

背景:從數據庫獲取時間傳到前端進行展示的時候,我們有時候可能無法得到一個滿意的時間格式的時間日期,在數據庫中顯示的是正確的時間格式,獲取出來卻變成了很丑的時間戳,@JsonFormat注解很好的解決了這個問題,我們通過使用@JsonFormat可以很好的解決:后台到前台時間格式保持一致的問題,其次,另一個問題是,我們在使用WEB服務的時,可能會需要用到,傳入時間給后台,比如注冊新用戶需要填入出生日期等,這個時候前台傳遞給后台的時間格式同樣是不一致的,而我們的與之對應的便有了另一個注解,@DataTimeFormat便很好的解決了這個問題,接下來記錄一下具體的@JsonFormat與DateTimeFormat的使用過程。

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date updateTime;

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM