标签:rest ace host dep line info intern tty rac
在项目中某些情况下接口需要返回的是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格式:
注意:
@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 }
标签:rest ace host dep line info intern tty rac
原文地址:https://www.cnblogs.com/echola/p/10955817.html