springboot post参数富文本 springboot post单个参数_springboot 返回json


  • spring boot 四种属性注入
  • spring boot 中常用注解
  • spring boot 自动配置
  • @RequestBody 和 @ResponseBody
  • @RequestBody
  • 作用
  • 使用时机
  • @ResponsseBody
  • 作用
  • 使用时机
  • 问题记录

spring boot 四种属性注入

  • @Autowired注入
  • 构造方法注入
  • @Bean和形参注入
  • 使用@bean和@ConfigurationProperties(prefx = "...")注入

spring boot 中常用注解

  • @EnableAutoConfiguration
  • @RestController
  • CompenScan
  • SpringBootApplication
  • SpringBootConfiguraion
  • @Configuration
  • @PropertySource
  • @Bean
  • @Value
  • ConfigurationProperties
  • EnableConfigurationProperties

spring boot 自动配置

@EnableAutoConfiguration开启spring boot自动配置,在Denpendcy中引入spring-boot-autoconfigure,这个依赖项中定义了许多的依赖、例如aop、cache、jdbc……


@RequestBody 和 @ResponseBody

@RequestBody

作用

@RequestBody(1)作用于读取Request请求的body部分数据,使用系统默认的HttpMessageConverter进行解析,然后把数据绑定到要返回的对象上;(2)把HttpMessageConverter返回的对象数据绑定到Controller方法的参数上


使用时机

  1. 使用GET、POST请求,根据request header content-type判断
  • application/x-www-form-urlencoded,可选(非必须项,这种格式的数据,使用 @ReauestBody,@RequestParm,@ModelAttribute都能处理)
  • mutilpart/form-data,这种格式数据 @RequestBody不能处理
  • 其他格式,必须(包括application/json、application/xml格式数据,必须使用 @RequestBody来处理)
  1. 使用PIUT请求,根据request header content-type判断
  • application/x-www-form-urlencoded,必须(这种格式数据必须使用 @RequestBody 处理)
  • mutilpart/form-data,不能(这种格式数据不能用 @RequestBody 处理)
  • 其他格式(application/json、application/xml,这种格式数据必须使用 @RequestBody 处理)

注意:request的body部分数据编码格式由conten-type指定


@ResponsseBody

作用

此注解作用于Controller方法的返回对象,通过HtppMessageConverter转换为指定格式后,写入Response的body中

使用时机

返回对象为json、xml这种格式的数据时使用


问题记录

  1. Spring Boot Application in default package

描述:建立如下测试程序,使用 @SpringBootApplication注解,报错:Spring Boot Application in default package


springboot post参数富文本 springboot post单个参数_spring_02


产生原因:main方法直接放在了java包下

解决方案


官方解决方案:
@springbootApplication 注解失效的情况下,推荐使用@CompentScan 和@EnableAutoConfiguration进行代替;


在java包下建立一个新的package,然后将测试程序移动到该package下,如下图:


springboot post参数富文本 springboot post单个参数_数据_03


  1. 启动spring boot项目失败

描述:如下图


springboot post参数富文本 springboot post单个参数_数据_04


原因:端口被占用

解决方案:在application.properties中配置端口,或者将占用当前端口的程序shutdown

  1. 没有配置Tomcat服务器,导启动失败

配置步骤如下:


1 编辑配置:Edit Configuration


springboot post参数富文本 springboot post单个参数_spring_05


2 选择 Template,选择Tomcat Server ——> Local


springboot post参数富文本 springboot post单个参数_springboot 返回json_06


springboot post参数富文本 springboot post单个参数_springboot 返回json_07


spring boot项目启动成功后日志如下:


springboot post参数富文本 springboot post单个参数_spring_08


在浏览器输入测试用的url,结果如下:


springboot post参数富文本 springboot post单个参数_springboot 返回json_09