简体   繁体   English

从Servlet调用JAX-RS服务

[英]Invoking JAX-RS service from a servlet

I'm currently working on a java web application using Eclipse. 我目前正在使用Eclipse开发Java Web应用程序。 I have created a web page servlet that asks the user to choose a file to upload, and I have a web service which I want to handle the file. 我创建了一个网页servlet,要求用户选择要上传的文件,并且我有一个要处理该文件的Web服务。

My issue is how to pass parameters from the servlet to the web service, and then invoke the service from the servlet. 我的问题是如何将参数从Servlet传递到Web服务,然后从Servlet调用服务。

I have tried methods using context and Httpconnections to do this but neither seemed to have work. 我尝试了使用上下文和Httpconnections进行此操作的方法,但似乎都没有用。

Any help or advice would be greatly appreciated! 任何帮助或建议,将不胜感激!

My code for the servlet: 我的servlet代码:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession(false);

    String uploadfile = request.getParameter("uploadfile");

    String Username = (String)session.getAttribute("Loginname");

    URL url = new URL ("http://localhost:9763/CWEngine_1.0.0/services/engine");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", MediaType.TEXT_PLAIN);

    Map<String, String> uname = new HashMap<String, String>();

    Map<String, String> ufile = new HashMap<String, String>();

    String output = uname.put("loginname", Username) + ufile.put("ufile", uploadfile);

    OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
    os.write(output);
    os.close();
}

My code for the web service: 我的Web服务代码:

@Path("/")
public class Engine {

@Context
private static ServletContext context;

@POST
@Consumes(MediaType.TEXT_PLAIN)

    public void main(String[] args) {

        URL url = null;
        HttpURLConnection connection = null;

        try {
            url = new URL ("http://localhost:9763/CWEngine_1.0.0/services/engine");
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            connection = (HttpURLConnection) url.openConnection();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        BufferedReader input = null;

        try {
            input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        //String output = uname.put("loginname", Username) + ufile.put("ufile", uploadfile);

        Map<String, String> uname = (Map<String, String>) ((ServletContext) input).getAttribute("uname");
        String username = uname.get("loginname");

        Map<String, String> ufile = (Map<String, String>) context.getAttribute("ufile");
        String uploadfile = ufile.get("ufile");

        System.out.println(uploadfile + username);

You can build rs Client in your servlet 您可以在servlet中构建rs Client

first, you have to build a rs client 首先,您必须建立一个rs客户

javax.ws.rs.client.Client client = ClientBuilder.newClient();

then point to your restful service url 然后指向您的宁静服务网址

WebTarget target = client.target("your restful service url");

and specify what kind of data you prefer to get, take xml for example 并指定您希望获取的数据类型,以xml为例

Builder builder = target.request(MediaType.APPLICATION_XML);

and last specify the http method, take get for example 最后指定http方法,以get为例

Type returnObj = builder.get(Type); 

once builder.get(Type) is executed, it will return an object whose type is "Type". 一旦执行builder.get(Type),它将返回一个类型为“ Type”的对象。 "Type" must be the same as the return type of your restful service. “类型”必须与您的静态服务的返回类型相同。

In your case, you need to use 在您的情况下,您需要使用

builder.post(Entity.entity("your input Object", "the media type"));

I use jersey the most, and here is the official site for your further reference about client API. 我使用球衣最多,这是您有关客户端API的进一步参考的官方网站。 https://jersey.java.net/documentation/latest/client.html https://jersey.java.net/documentation/latest/client.html


I'll give you a simple runnable example 我给你一个简单的例子

my pom dependency 我对pom的依赖

<dependencies>
        <!-- jackson json dependency -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.6.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.6.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.6.5</version>
        </dependency>


        <!-- jersey dependency -->
        <dependency>
            <groupId>org.glassfish.jersey.bundles</groupId>
            <artifactId>jaxrs-ri</artifactId>
            <version>2.21.1</version>
        </dependency>

        <!-- make jersey auto marshel to json -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
            <version>2.21.1</version>
        </dependency>


        <!-- make jersey auto marshel to xml -->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-jaxb</artifactId>
            <version>2.21.1</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.woodstox</groupId>
            <artifactId>stax2-api</artifactId>
            <version>3.1.4</version>
        </dependency>
    </dependencies>

my rest config 我的休息配置

package com.blithe.rest;

import javax.ws.rs.*;
import org.glassfish.jersey.server.*;

@ApplicationPath("/services")
public class RESTServiceConfig extends ResourceConfig
{
        public RESTServiceConfig(){

            packages("com.blithe.rest","com.blithe.resource");
        }

}

a simple resource 简单的资源

package com.blithe.resource;

import java.util.ArrayList;
import java.util.List;

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

@Path("helloworld")
public class HelloWorldResource
{    
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public List<String> getStringArray(){

        List<String> list = new ArrayList<>();
        list.add("hello");
        list.add("world");
        return list;
    }     
}

and a rs client 和一个rs客户

package com.blithe.client;

import java.util.List;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;

public class RSClient {

    public static void main(String [] args){

        Client client = ClientBuilder.newClient();

        WebTarget target = client.target("http://localhost:8080/RestPOM/services/helloworld");

        Builder builder = target.request(MediaType.APPLICATION_JSON);

        List<String> list  =builder.post(null , new GenericType<List<String>>(){});


            System.out.println(list.get(0)+list.get(1));
// the out put will be helloworld
        }
    }

Run the project on server to publish restful service, and then run the main() method. 在服务器上运行项目以发布静态服务,然后运行main()方法。 You should see helloworld on console. 您应该在控制台上看到helloworld。

What you need to do is, make a rs client in your servlet. 您需要做的是在servlet中创建一个rs客户端。 You can refer to RSClient above. 您可以参考上面的RSClient。

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

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