0

我正在尝试使用 Java 创建一个非常简单的 REST Web 服务,但我无法正确映射...

这是我的服务:

package rest;

@Path("/square/{num}")
public class SquareNumberRest {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String squareNum(@PathParam("num") String num) {
        int n = Integer.parseInt(num);
        int squared = n * n;
        JSONObject jo = new JSONObject(squared);
        return jo.toString();
    }
}

我的 web.xml 描述符:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>TestProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>rest</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>
</web-app>

我尝试使用以下 URL 上的服务: http://localhost:8080/MyProjectName/square/3

但我收到 404 错误。

4

1 回答 1

1

您是否为项目定义了 URL 上下文?项目的 URL 根目录可能在 localhost:8080 上,这意味着您需要这样做

http://localhost:8080/square/3代替。

于 2018-02-07T23:57:21.547 回答