简体   繁体   English

REST Web服务的端点发布

[英]Endpoint Publish for REST Web Services

I've published JAX-WS web services with Endpoint.publish during development. 我在开发期间使用Endpoint.publish发布了JAX-WS Web服务。 Is there any such utility class exists (in JAX-RS) for publishing REST web services in jersey? 是否存在用于在泽西发布REST Web服务的任何此类实用程序类(在JAX-RS中)? I referred couple of articles, and majority of them are based on publishing the web services in some containers like Jetty, Grizzly etc. 我引用了几篇文章,其中大部分是基于在Jetty,Grizzly等一些容器中发布Web服务。

Jersey-Grizzly has a very simple solution. Jersey-Grizzly有一个非常简单的解决方案。 From https://github.com/jesperfj/jax-rs-heroku : 来自https://github.com/jesperfj/jax-rs-heroku

package embedded.rest.server;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;

@Path("/hello")
public class Main {

    public static void main(String[] args) {        
        final String baseUri = "http://localhost:7080/";
        final Map<String, String> initParams = new HashMap<String, String>();

        // Register the package that contains your javax.ws.rs-annotated beans here
        initParams.put("com.sun.jersey.config.property.packages","embedded.rest.server");

        System.out.println("Starting grizzly...");
        try {
            SelectorThread threadSelector =
                    GrizzlyWebContainerFactory.create(baseUri, initParams);
            System.out.println(String.format("Jersey started with WADL "
                    + "available at %sapplication.wadl.", baseUri));
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Well, this was easy!";
    }
}

If you're using Maven, you'll need the following three dependencies: 如果您使用的是Maven,则需要以下三个依赖项:

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-grizzly</artifactId>
    <version>1.15</version>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-bundle</artifactId>
    <version>1.15</version>
</dependency>
<dependency>
    <groupId>com.sun.grizzly</groupId>
    <artifactId>grizzly-servlet-webserver</artifactId>
    <version>1.9.18-i</version>
</dependency>

To test it, just open http://localhost:7080/hello in a browser. 要测试它,只需在浏览器中打开http://localhost:7080/hello

I think you can use Provider interface to publishing a RESTful Web Service with JAX-WS. 我认为您可以使用Provider接口通过JAX-WS发布RESTful Web服务。

The example class: 示例类:

@WebServiceProvider
@BindingType(value=HTTPBinding.HTTP_BINDING)
public class AddNumbersImpl implements Provider {

    @Resource
    protected WebServiceContext wsContext;

    public Source invoke(Source source) {
        try {
            MessageContext mc = wsContext.getMessageContext();
            // check for a PATH_INFO request
            String path = (String)mc.get(MessageContext.PATH_INFO);
            if (path != null && path.contains("/num1") &&
                       path.contains("/num2")) {
                return createResultSource(path);
            }
            String query = (String)mc.get(MessageContext.QUERY_STRING);
            System.out.println("Query String = "+query);
            ServletRequest req = (ServletRequest)mc.get(MessageContext.SERVLET_REQUEST);
            int num1 = Integer.parseInt(req.getParameter("num1"));
            int num2 = Integer.parseInt(req.getParameter("num2"));
            return createResultSource(num1+num2);
        } catch(Exception e) {
            e.printStackTrace();
            throw new HTTPException(500);
        }
    }

    private Source createResultSource(String str) {
        StringTokenizer st = new StringTokenizer(str, "=&/");
        String token = st.nextToken();
        int number1 = Integer.parseInt(st.nextToken());
        st.nextToken();
        int number2 = Integer.parseInt(st.nextToken());
        int sum = number1+number2;
        return createResultSource(sum);
    }

    private Source createResultSource(int sum) {
        String body =
            "<ns:addNumbersResponse xmlns:ns="http://java.duke.org"><ns:return>"
            +sum
            +"</ns:return></ns:addNumbersResponse>";
        Source source = new StreamSource(
            new ByteArrayInputStream(body.getBytes()));
        return source;
    }   
}

To deploy our endpoint on a servlet container running with the JAX-WS RI we need to create a WAR file. 要在使用JAX-WS RI运行的servlet容器上部署端点,我们需要创建一个WAR文件。

The adjusted web.xml: 调整后的web.xml:

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee">
  <listener>
    <listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener
  </listener>
  <servlet>
    <servlet-name>restful-addnumbers</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>restful-addnumbers</servlet-name>
    <url-pattern>/addnumbers/*</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>60</session-timeout>
  </session-config>
</web-app>

and need to add sun-jaxws.xml deployment descriptor to the WAR file. 并需要将sun-jaxws.xml部署描述符添加到WAR文件中。

<endpoints
    xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
    version="2.0">

    <endpoint
        name="restful-addnumbers"
        implementation="restful.server.AddNumbersImpl"
        wsdl="WEB-INF/wsdl/AddNumbers.wsdl"
        url-pattern="/addnumbers/*" />
</endpoints>

Or could be create simple HttpServer 或者可以创建简单的HttpServer

import java.io.IOException;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;

public class YourREST {

    static final String BASE_URI = "http://localhost:9999/yourrest/";

    public static void main(String[] args) {
        try {
            HttpServer server = HttpServerFactory.create(BASE_URI);
            server.start();
            System.out.println("Press Enter to stop the server. ");
            System.in.read();
            server.stop(0);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

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