简体   繁体   English

Java:REST服务URL映射

[英]Java: REST service URL mapping

I am trying to create a very simple REST web service using Java, but I can't get the mapping right... 我正在尝试使用Java创建一个非常简单的REST Web服务,但是我无法正确映射。

This is my service: 这是我的服务:

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();
    }
}

My web.xml descriptor: 我的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>

I try to consume the service on the following URL: http://localhost:8080/MyProjectName/square/3 我尝试在以下URL上使用该服务: http:// localhost:8080 / MyProjectName / square / 3

but I'm getting a 404 error. 但出现404错误。

Did you define the URL context for the project? 您是否为项目定义了URL上下文? It's possible that the URL root for the project is right on localhost:8080, which means you'll need to do 该项目的URL根目录可能就在localhost:8080上,这意味着您需要

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM