Springboot xmlとjsonフォーマットの戻り

2807 ワード

Spring bootのrestインタフェース戻りフォーマットは、RequestMapping注記のproducesで指定できます.プロジェクトがjsonとxmlの戻りフォーマットを同時に満たす必要がある場合は、次のように手動で指定する必要があります.
@RequestMapping(value = "/student", produces = arrayOf("application/xml", "application/json"))

その中のアプリケーション/xmlとアプリケーション/jsonはxmlまたはjsonを使用して結果を返すことを表しますが、どのフォーマットを返すべきかは何で判断しますか?これは主に呼び出し者によって指定されます.
义齿jsonの最後はjson形式で返されます.xmlの最後はxml形式で返されます.たとえば、次のようにします.http://localhost:8080/student.json?id=1
  • 導入パケット依存
  • 
       com.fasterxml.jackson.dataformat
       jackson-dataformat-xml
    
    
  • 2 xmlコンバータ
  • を追加
    @Configuration
    open class MyWebConfiguration : WebMvcConfigurerAdapter() {
        @Bean
        open fun jacksonXmlConverter() = MappingJackson2XmlHttpMessageConverter()
    
        override fun configureMessageConverters(converters: List>) {
            (converters as MutableList).add(jacksonXmlConverter())
        }
    }
    
  • 3エンティティクラスを新規作成します.ここではh 2メモリデータベースを使用して
  • を実証します.
    @Entity
    data class Student (val name: String, val age: Int, @Id @GeneratedValue(strategy=GenerationType.AUTO) var id: Int = 0) {    
      constructor() : this("", 0)
    }
    interface StudentRepository : JpaRepository
    
  • 4試験例
  • を記述する
    @SpringBootApplication
    @RestController
    open class ProfileDemoApplication : CommandLineRunner {
        @Autowired
        private lateinit var repo: StudentRepository
        override fun run(vararg p0: String?) {
            with(repo) {
                //          
                save(Student("aaa", 10))
                save(Student("bbb", 20))
                save(Student("ccc", 30))
            }
            println("students are ${repo.findAll()}")
        }
        @RequestMapping("/hello")
        fun sayHello() = "hello world"
        @RequestMapping(value = "/student", produces = arrayOf("application/json", "application/xml"))
        fun getStudentById(id: Int) : Student = repo.findOne(id)
        companion object {
            @JvmStatic
            fun main(args: Array) {
                SpringApplication.run(ProfileDemoApplication::class.java, *args)
            }
        }
    }
    
  • 4テスト、ブラウザで入力http://localhost:8080/student.xml?id=1結果は、
  • です.
    
    aaa
    10
    1
    
    

    入力時http://localhost:8080/student.json?id=1の場合は次のようになります.
    {"name":"aaa","age":10,"id":1}
    

    注意すべき点
  • kotlinのデフォルトのクラスと関数はfinalであるため、@Configurationおよび@Beanによって修飾されたすべてのクラスまたは関数はopenとして定義される.主にspringが関連エージェントクラス
  • を生成する必要があるためである.