spring mvc @ResponseStatus 和 ResponseEntity

@ResponseStatus 是标记一个方法或异常类在返回时响应的http状态。其代码注释如下:

*
* <p>The status code is applied to the HTTP response when the handler
* method is invoked and overrides status information set by other means,
* like {@code ResponseEntity} or {@code "redirect:"}.
*
* <p><strong>Warning</strong>: when using this annotation on an exception
* class, or when setting the {@code reason} attribute of this annotation,
* the {@code HttpServletResponse.sendError} method will be used.
*
* <p>With {@code HttpServletResponse.sendError}, the response is considered
* complete and should not be written to any further. Furthermore, the Servlet
* container will typically write an HTML error page therefore making the
* use of a {@code reason} unsuitable for REST APIs. For such cases it is
* preferable to use a {@link org.springframework.http.ResponseEntity} as
* a return type and avoid the use of {@code @ResponseStatus} altogether.
*
* <p>Note that a controller class may also be annotated with
* {@code @ResponseStatus} and is then inherited by all {@code @RequestMapping}
* methods.

@ResponseStatus 可以结合 @ResponseBody 一起使用。

@RequestMapping("/testResponseBody")
@ResponseBody
public Map<String, String> testResponseBody(){
    return ImmutableMap.of("key", "value");
}


@RequestMapping("/testResponseBodyFaild")
@ResponseBody
@ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
public Map<String, String> testResponseBodyFaild(){
    return ImmutableMap.of("key", "faild");
}

这两个handler method返回的http status code(http状态码) 分别是200 和 501。

ResponseEntity 是在 org.springframework.http.HttpEntity 的基础上添加了http status code(http状态码),用于RestTemplate以及@Controller的HandlerMethod。它在Controoler中或者用于服务端响应时,作用是和@ResponseStatus与@ResponseBody结合起来的功能一样的。用于RestTemplate时,它是接收服务端返回的http status code 和 reason的。
代码注释如下:

 * Extension of {@link HttpEntity} that adds a {@link HttpStatus} status code.
 * Used in {@code RestTemplate} as well {@code @Controller} methods.
 *
 * <p>In {@code RestTemplate}, this class is returned by
 * {@link org.springframework.web.client.RestTemplate#getForEntity getForEntity()} and
 * {@link org.springframework.web.client.RestTemplate#exchange exchange()}:
 * <pre class="code">
 * ResponseEntity&lt;String&gt; entity = template.getForEntity("http://example.com", String.class);
 * String body = entity.getBody();
 * MediaType contentType = entity.getHeaders().getContentType();
 * HttpStatus statusCode = entity.getStatusCode();
 * </pre>
 *
 * <p>Can also be used in Spring MVC, as the return value from a @Controller method:
 * <pre class="code">
 * &#64;RequestMapping("/handle")
 * public ResponseEntity&lt;String&gt; handle() {
 *   URI location = ...;
 *   HttpHeaders responseHeaders = new HttpHeaders();
 *   responseHeaders.setLocation(location);
 *   responseHeaders.set("MyResponseHeader", "MyValue");
 *   return new ResponseEntity&lt;String&gt;("Hello World", responseHeaders, HttpStatus.CREATED);
 * }
 * </pre>
 * Or, by using a builder accessible via static methods:
 * <pre class="code">
 * &#64;RequestMapping("/handle")
 * public ResponseEntity&lt;String&gt; handle() {
 *   URI location = ...;
 *   return ResponseEntity.created(location).header("MyResponseHeader", "MyValue").body("Hello World");
 * }
 * </pre>

ResponseEntity 和 @ResponseStatus 一起使用是无效的

@RequestMapping("/testResponseEntity")
public ResponseEntity<Map<String, String>> testResponseEntity(){
    Map<String, String> map = ImmutableMap.of("key", "value");
    return ResponseEntity.ok(map);
}

@RequestMapping("/testResponseEntityFaild")
@ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
public ResponseEntity<Map<String, String>> testResponseEntityFaild(){
    Map<String, String> map = ImmutableMap.of("key", "faild");
    return ResponseEntity.ok(map);
}


@RequestMapping("/testResponseEntityFaild2")
public ResponseEntity<Map<String, String>> testResponseEntityFaild2(){
    return ResponseEntity.badRequest().body(ImmutableMap.of("key", "faild"));
}

这三个handler method返回的http status code(http状态码) 分别是200 、 200 和 400。

完整的TestController代码

 import com.google.common.collect.ImmutableMap;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Created by saleson on 2017/5/5.
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @RequestMapping("/testResponseEntity")
    public ResponseEntity<Map<String, String>> testResponseEntity(){
        Map<String, String> map = ImmutableMap.of("key", "value");
        return ResponseEntity.ok(map);
    }

    @RequestMapping("/testResponseEntityFaild")
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
    public ResponseEntity<Map<String, String>> testResponseEntityFaild(){
        Map<String, String> map = ImmutableMap.of("key", "faild");
        return ResponseEntity.ok(map);
    }


    @RequestMapping("/testResponseEntityFaild2")
    public ResponseEntity<Map<String, String>> testResponseEntityFaild2(){
        return ResponseEntity.badRequest().body(ImmutableMap.of("key", "faild"));
    }


    @RequestMapping("/testResponseBody")
    @ResponseBody
    public Map<String, String> testResponseBody(){
        return ImmutableMap.of("key", "value");
    }

    @RequestMapping("/testResponseBodyFaild")
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_IMPLEMENTED)
    public Map<String, String> testResponseBodyFaild(){
        return ImmutableMap.of("key", "faild");
    }
}

返回的http status code截图:

这里写图片描述

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现文件上传和下载在Spring MVC中非常简单,下面是具体的实现步骤: 文件上传: 1. 在Spring配置文件中添加以下bean配置: ```xml <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> <property name="maxUploadSize" value="10485760" /> </bean> ``` 其中,`defaultEncoding`属性用于设置上传文件的编码格式,`maxUploadSize`属性用于设置最大上传文件的大小。 2. 在Controller中添加文件上传方法: ```java @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { String fileName = file.getOriginalFilename(); String filePath = "/path/to/save/" + fileName; try { file.transferTo(new File(filePath)); return "上传成功!"; } catch (IOException e) { e.printStackTrace(); } } return "上传失败,请选择文件!"; } ``` 其中,`@RequestParam`用于获取上传的文件,`file`是表单中文件上传控件的name属性值。 文件下载: 1. 在Controller中添加文件下载方法: ```java @RequestMapping(value = "/download", method = RequestMethod.GET) public ResponseEntity<byte[]> download() throws IOException { String filePath = "/path/to/file"; File file = new File(filePath); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", file.getName()); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); } ``` 其中,`filePath`为要下载的文件路径,`FileUtils.readFileToByteArray(file)`用于将文件转换成字节数组。 2. 在JSP页面中添加下载链接: ```html <a href="/download">下载文件</a> ``` 至此,完成了Spring MVC中文件上传和下载的实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值