简体   繁体   中英

My rest service does not work

I am trying to make a rest call but it does not work.

My project explorer is;

我的项目浏览器是

My web.xml is;

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>HelloRest</display-name>
  <servlet-mapping>
    <servlet-name>javax.ws.rs.core.Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
  <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>
</web-app>

IHello.java;

@Path("hello")
public interface IHello {
    @GET
    @Path("sayHello")
    public String sayHello(@QueryParam("name") String name);
}

Hello.java;

public class Hello implements IHello {
    @Override
    public String sayHello(String name) {
        return "Hello: " + name;
    }
}

I call it from browser with;

 http://localhost/HelloRest/rest/hello/sayHello?name=me

but it returns Not found.

If I call;

http://localhost/HelloRest/aa/index.html,

I can see the content of index.hmtl.

What is my problem and how can I fix it?

Note: I deploy it with Wildfly-10.1

Try to change your Servlet deployment code as given below. With this deployment all the @Path classes found in your web application will be available with the URL pattern /rest/*

<servlet>
    <servlet-name>javax.ws.rs.core.Application</servlet-name>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>javax.ws.rs.core.Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

@Narayana's answer is perfectly valid but you could instead forgo the web.xml all together and have a single additional Java file that, for now, lives in the same directory as your code and looks something like:

package hellorest;

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

/**
 * Used to bootstrap the rest services.  This class is not directly used.
 */
@ApplicationPath("/services")
public class RestApplicationConfig extends Application {
    // intentionally empty
}

Notice the "/services" annotation - this says that your services will be accessed at /services so in your example it is likely to be http://localhost:8080/HelloRest/services/hello/sayHello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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