SpringMVC常用注解及HTTP数据转换的原理

2023-06-06  本文已影响0人  liushiping

一、SpringMVC的四种传参注解

HTTP协议组成 协议内容示例 对应Spring注解
path info传参 /articles/12 (查询id为12的文章,12是参数) @PathVariable
URL Query String传参 /articles?id=12 @RequestParam
Body 传参 Content-Type: multipart/form-data @RequestParam
Body 传参 Content-Type: application/json,或其他自定义格式 @RequestBody
Headers 传参 @RequestHeader

二、SpringMVC常用注解详解

2.1 @RequestBody与@ResponseBody

2.2. @RequestMapping注解

@RequestMapping注解是所有常用注解中,最有看点的一个注解,用于标注HTTP服务端点。它的很多属性对于丰富我们的应用开发方式方法,都有很重要的作用。如:

@RequestMapping还有一种简化写法,及将method的含义附加到注解中,如:@GetMapping、@PostMapping、@PutMapping、@DeleteMapping等;

2.3 @RestController与@Controller

@Controller注解是开发中最常使用的注解,它的作用有两层含义:

@RestController相当于 @Controller和@ResponseBody结合。它有两层含义:

2.4 @PathVariable 与@RequestParam

PathVariable用于URI上的{参数},如下方法用于删除一篇文章,其中id为文章id。如:我们的请求URL为“/article/1”,那么将匹配DeleteMapping并且PathVariable接收参数id=1。而RequestParam用于接收普通表单方式或者ajax模拟表单提交的参数数据。

@GetMapping("/article/{id}")
public @ResponseBody Article getArticle(@PathVariable Long id)

三、Http数据转换的原理

Http数据转换的原理
实现类 功能说明
StringHttpMessageConverter 将请求信息转为字符串
FormHttpMessageConverter 将表单数据读取到MultiValueMap中
XmlAwareFormHttpMessageConverter 扩展与FormHttpMessageConverter,如果部分表单属性是XML数据,可用该转换器进行读取
ResourceHttpMessageConverter 读写org.springframework.core.io.Resource对象
BufferedImageHttpMessageConverter 读写BufferedImage对象
ByteArrayHttpMessageConverter 读写二进制数据
SourceHttpMessageConverter 读写java.xml.transform.Source类型的对象
MarshallingHttpMessageConverter 通过Spring的org.springframework,xml.Marshaller和Unmarshaller读写XML消息
Jaxb2RootElementHttpMessageConverter 通过JAXB2读写XML消息,将请求消息转换为标注的XmlRootElement和XmlType连接的类中
MappingJacksonHttpMessageConverter 利用Jackson开源包的ObjectMapper读写JSON数据
RssChannelHttpMessageConverter 读写RSS种子消息
AtomFeedHttpMessageConverter 和RssChannelHttpMessageConverter能够读写RSS种子消息

根据HTTP协议的Accept和Content-Type属性,以及参数数据类型来判别使用哪一种HttpMessageConverter。当使用RequestBody或ResponseBody时,再结合前端发送的Accept数据类型,会自动判定优先使用MappingJacksonHttpMessageConverter作为数据转换器。

四、自定义HttpMessageConverter

其实绝大多数的数据格式都不需要我们自定义HttpMessageConverter,都有第三方类库可以帮助我们实现(包括下文代码中的Excel格式)。但有的时候,有些数据的输出格式并没有类似于Jackson这种类库帮助我们处理,需要我们自定义数据格式。该怎么做?

下面我们就以Excel数据格式为例,写一个自定义的HTTP类型转换器。实现的效果就是,当我们返回ExcelResponse这种数据类型的话,就自动将ExcelResponse转成Excel数据响应给客户端。

@Service
public class ExcelHttpMessageConverter extends AbstractHttpMessageConverter<ExcelResponse> {

    private static final MediaType EXCEL_TYPE = MediaType.valueOf("application/vnd.ms-excel");

    ExcelHttpMessageConverter () {
        super(EXCEL_TYPE);
    }

    @Override
    protected ExcelResponse readInternal(final Class<? extends ExcelResponse> clazz,
                                final HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        return null;
    }

    //针对ExcelResponse类型返回值,使用下面的writeInternal方法进行消息类型转换
    @Override
    protected boolean supports(final Class<?> clazz) {
        return (ExcelResponse.class == clazz);
    }

    @Override
    protected void writeInternal(final ExcelResponse excelResponse, final HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {

        final Workbook workbook = new HSSFWorkbook();
        final Sheet sheet = workbook.createSheet();

        final Row row = sheet.createRow(0);
        row.createCell(0).setCellValue(excelResponse.getMessage());
        row.createCell(1).setCellValue(excelResponse.getData().toString());

        workbook.write(outputMessage.getBody());
    }
}
上一篇下一篇

猜你喜欢

热点阅读