gpt4 book ai didi

java - 尝试返回 XML 时 Jersey 返回 500

转载 作者:行者123 更新时间:2023-12-01 23:43:17 24 4
gpt4 key购买 nike

我在使用 Jersey 2.29 时遇到问题。这是一个简单的例子。我设法返回纯文本,但如果我尝试返回 XML,则会收到 500 错误。

我的步骤:

启动服务器。前往http://localhost:8080/demorest/webapi/aliens 。我我会得到500。

当我重写此示例以返回纯文本时,一切正常。但对于 XML 来说是一个问题。

我看这里: Jersey returns 500 when trying to return an XML response但这对我不起作用。

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.test.demorest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>

外星人.java

package com.test.demorest;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Alien {

private String name;
private int points;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}

}

AlienResource.java

package com.test.demorest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;


@Path("aliens")
public class AlienResource {

@GET
@Produces(MediaType.APPLICATION_XML)
public Alien getAlien() {
System.out.println("getAlien called...");
Alien a1 = new Alien();
a1.setName("Adam");
a1.setPoints(23);

return a1;
}

}

最佳答案

将其添加到 pom.xml 中的依赖项

   <dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0-b170201.1204</version>
</dependency>

<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>

<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0-b170127.1453</version>
</dependency>

关于java - 尝试返回 XML 时 Jersey 返回 500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58250336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com