gpt4 book ai didi

java - JAX-RS、GlassFish、Eclipse。一个简单的网络服务不起作用

转载 作者:行者123 更新时间:2023-11-29 05:23:53 25 4
gpt4 key购买 nike

我正在尝试在我的机器上运行一个简单的“Hello World”RESTful Web 服务。我使用 Eclipse Kepler 和 GlassFish 4.0。我能够部署该服务并在 GlassFish 的管理页面上看到它,但是当我尝试访问它时出现以下错误:“HTTP 状态 404 - 未找到”。

这里是简单服务的代码:

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;

@Path("hello")
public class HelloRest {
@SuppressWarnings("unused")
@Context
private UriInfo context;

/**
* Default constructor.
*/
public HelloRest() {
// TODO Auto-generated constructor stub
}

/**
* Retrieves representation of an instance of HelloRest
* @return an instance of String
*/
@GET
@Produces("application/xml")
public String getXml() {
// TODO return proper representation object
return "<greeting>Hello REST</greeting>";
}

/**
* PUT method for updating or creating an instance of HelloRest
* @param content representation for the resource
* @return an HTTP response with content of the updated or created resource.
*/
@PUT
@Consumes("application/xml")
public void putXml(String content) {
}

}

为了访问该服务,我尝试了以下 URL:http://127.0.0.1:8080/hello-rest/hello,其中 hello-rest是Eclipse项目的名称,也是GlassFish管理页面建议的根路径。

最佳答案

您的代码似乎没问题,所以问题很可能是您没有为您的服务定义基本 url。您需要告诉 JAX-RS(Jersey 是 GlassFish 中的实现)它必须拦截哪个 url 模式作为您的端点(基本 url)。

实现此目的的一种方法是使用可以添加到项目中任何包的应用程序类(您也可以在我不会介绍的 web.xml 文件中定义必要的)。以下是代码:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("your-base-url")
public class ApplicationConfig extends Application {

}

您使用@ApplicationPath 注释来定义您的基本网址。然后,您可以在 http://127.0.0.1:8080/hello-rest/your-base-url/hello

访问您的服务

关于java - JAX-RS、GlassFish、Eclipse。一个简单的网络服务不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508159/

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