我正在使用这个名为 CLAWS-Dicionario
的测试项目,并且我正在尝试在 Glassfish 服务器上运行它(该服务器运行完美)。我所拥有的就是该类:
package com.k19.restful.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/helloworld")
public class HelloWorldResource {
@GET
@Produces("text/plain")
public String showHelloWorld() {
return "Olá mundo!";
}
}
并在 web.xml 中添加此内容,以便将 Jersey 合并到其中
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.k19.restful.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
我还将以下 Jersey 库添加到我的构建路径中:
asm-debug-all-5.0.3.jar
javax.ws.rs-api-2.0.1.jar
jersey-server.jar
org.osgi.core-4.2.0
所以我运行了这个项目,一切都感觉很好。但是当我尝试访问此 URL 时:
http://localhost:8080/CLAWS-Dicionario/helloworld
它返回 404 错误。我确定主机配置在 8080 端口(URL localhost:8080 工作得很好)。那么问题出在哪里呢?
编辑:服务器开始出现另一个问题,这将我带到了 domain.xml
文件的那一行:
<application context-root="/CLAWS_-_Dicionário" object-type="user" name="CLAWS-Dicionario" directory-deployed="true" location="${com.sun.aas.instanceRootURI}/eclipseApps/CLAWS-Dicionario/">
修复CLAWS_-_Dicionário
部分。这是我的项目的真实名称吗?我必须删除重音才能使服务器正常工作,并且在运行项目时我发现没有更多控制台响应...即使我尝试 URL http://localhost:8080/CLAWS__-_Dicionario/helloworld
,错误仍然存在,所以...只是发现有一些重要的事情要指出。
最佳答案
根据您使用的 Servlet 版本,您需要:
对于 Servlet 2.x 实现:
- jersey-container-servlet-core.jar
对于 Servlet 3.x 实现:
- jersey-container-servlet.jar
org.glassfish.jersey.servlet.ServletContainer 未打包在 jersey-server.jar 中
根据类 ServletContainer 的 api 文档
If the initialization parameter is not present and a initialization parameter "jersey.config.server.provider.packages" is present (see ServerProperties.PROVIDER_PACKAGES) a new instance of ResourceConfig with this configuration is created. The initialization parameter "jersey.config.server.provider.packages" MUST be set to provide one or more package names. Each package name MUST be separated by ';'.
参数com.sun.jersey.config.property.packages
在版本2.x中已被jersey.config.server.provider.packages
取代。
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.k19.restful.resources</param-value>
</init-param>
在 domain.xml
中,您应该有 context-root
表示可访问应用程序的 url 路径:
<application context-root="/CLAWS-Dicionario" object-type="user" name="CLAWS-Dicionario" directory-deployed="true" location="${com.sun.aas.instanceRootURI}/eclipseApps/CLAWS-Dicionario/">
让您可以通过以下方式访问您的应用程序:
http://localhost:8080/CLAWS-Dicionario/helloworld
关于java - REST Web 项目出现 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32057923/