在项目中某些情况下接口需要返回的是xml数据或者json数据
1、在springboot项目加入依赖jackson-dataformat-xml
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.2.RELEASE</version> </dependency>
2、在pojo层添加User类
package com.example.demo.pojo; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * 被@XMLRootElement注解的类User,被描述为一个顶层的XML element */ @XmlRootElement public class User { String userName; String userAge; String userAddress; public User(String userName, String userAge, String userAddress) { this.userName = userName; this.userAge = userAge; this.userAddress = userAddress; } /** * 该注解可以将被注解的(非静态)字段,或者被注解的get/set方法对应的字段映射为本地元素,也就是子元素。 */ @XmlElement public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @XmlElement public String getUserAge() { return userAge; } public void setUserAge(String userAge) { this.userAge = userAge; } @XmlElement public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } }
3、在controller层添加UserController.java
package com.example.demo.controller; import com.example.demo.pojo.User; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { //http://localhost:8080/json @GetMapping(value = "/json",produces = MediaType.APPLICATION_JSON_VALUE) public User index(){ User user = new User("echola", "22", "深圳"); return user; } //http://localhost:8080/xml @GetMapping(value = "/xml",produces = MediaType.APPLICATION_XML_VALUE) public User XML(){ User user = new User("echola", "22", "深圳"); return user; } }
启动项目成功后,输入http://localhost:8080/json,页面上的json字符串:
输入http://localhost:8080/xml,页面上Xml格式:
注意:
- @Controller和RestController的区别
- @RestController注解相当于@ResponseBody+@Controller合在一起的作用。但是不能返回jsp,html页面,视图解析器InternalResourceViewSolver不起作用,无法解析jsp,html页面,只能返回Return中的内容
- 若返回到指定的页面,需要@Controller配合视图解析器才可以。如返回Json,Xml或自定义的ModiaType内容到页面中,则需要在对应的方法上添加@ResponseBody
- @RequestMapping和@GetMapping、@PostMapping(@PutMapping、@DeleteMapping)的区别
- GetMapping用于处理Get类型的方法,@PostMapping用于处理Post类型的方法等
- 传统的@requestMapping注释实现URI处理程序,拿么它应该是:
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
- 新方法可以简化为:
@GetMapping("/get/{id}")
查看@GetMapping注释的源代码,我们可以看到它已经通过以下方式使用RequestMethod.Get进行了注释:
@Target({ java.lang.annotation.ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @RequestMapping(method = { RequestMethod.GET }) public @interface GetMapping { // abstract codes }标签:xml,userAddress,springboot,userAge,json,User,public,String From: https://www.cnblogs.com/kn-zheng/p/17054950.html