【问题标题】:"org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation" to produce xml response“org.springframework.web.HttpMediaTypeNotAcceptableException:找不到可接受的表示”以产生 xml 响应
【发布时间】:2019-03-27 03:59:36
【问题描述】:

我尝试从 spring boot restcontroller 生成 xml 格式的数据。以下是用户型号代码。

@Entity  
@Table(name="BlogUser")
@XmlRootElement
public class User {

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  @Column(name="USER_ID", nullable = false, unique = true)
  private Long id;

  @Column(unique=true, nullable=false)
  @Length(min=2, max=30)
  @NotEmpty
  private String username;

  @Column(nullable=false)
  @Length(min=5)
  @NotEmpty
  private String password;

  @Column
  @Email
  @NotEmpty
  private String email;

  @Column
  @NotEmpty
  private String fullname;

  @Column
  private UserRole role;
}

而下面的代码是 RestController.java

@RestController
@RequestMapping(value="/rest/user")
@SessionAttributes("user")
public class UserRestController {
  @Autowired
  private UserService userService;

  @GetMapping(value="getAllUser", produces=MediaType.APPLICATION_XML_VALUE)
  public ResponseEntity<List<User>> getAllPost() {
    List<User> users = this.userService.findAll();

    if(users == null || users.isEmpty())
      return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
      return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }
  }
}

成功返回Json格式数据。但不会生成 xml 格式的值。它会引发以下异常。

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]

我将一些依赖项添加到 pom.xml 中,如下所示,

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

但仍然抛出相同的异常。我无法理解我想解决这个问题的原因。

【问题讨论】:

  • 你能发布你的用户类吗?
  • 我已经发布了用户类。
  • 也尝试在您的控制器端点中设置consumes=MediaType.APPLICATION_XML_VALUE
  • 对不起,我错过了它,因为它被标记为@Entity。通常,我不会将实体与 DTO 混为一谈。尝试在 User 类中生成 getter 和 setter。
  • 感谢您的回复。我使用 lombok 生成 getter/setter 方法。但是抛出了同样的异常。

标签: java spring-boot spring-restcontroller xml-binding


【解决方案1】:

@GetMapping 注释中设置consumes 属性。

@GetMapping(value = "getAllUser", produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE)

【讨论】:

    【解决方案2】:

    (代表问题作者发布).

    我修改方法如下:

    @GetMapping(value="getAllUser", produces = { "application/xml", "text/xml" }, consumes = MediaType.ALL_VALUE)
        public ResponseEntity<List<User>> getAllPost() {
    ..
    

    它完美地工作。它返回 xml 类型的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 2016-09-28
      相关资源
      最近更新 更多