从servlet调用JAX-RS服务

时间:2016-03-17 09:57:13

标签: java eclipse web-services servlets

我目前正在使用Eclipse开发java Web应用程序。我创建了一个网页servlet,要求用户选择要上传的文件,并且我有一个我想要处理该文件的Web服务。

我的问题是如何将参数从servlet传递到Web服务,然后从servlet调用服务。

我尝试过使用上下文和Httpconnections来完成这项工作的方法,但似乎都没有工作。

非常感谢任何帮助或建议!

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

我的网络服务代码:

@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);

1 个答案:

答案 0 :(得分:0)

您可以在servlet中构建rs Client

首先,你必须建立一个rs客户端

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

然后指向您的宁静服务网址

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

并指定您希望获得的数据类型,例如使用xml

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

并最后指定http方法,以get为例

Type returnObj = builder.get(Type); 

执行builder.get(Type)后,它将返回一个类型为“Type”的对象。 “类型”必须与您的休息服务的返回类型相同。

在您的情况下,您需要使用

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

我最常使用泽西,这里是关于客户端API的进一步参考的官方网站。 https://jersey.java.net/documentation/latest/client.html

我会给你一个简单的可运行的例子

我的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>

我的休息配置

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

}

一个简单的资源

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

和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
        }
    }

在服务器上运行项目以发布restful服务,然后运行main()方法。你应该在控制台上看到helloworld。

您需要做的是在servlet中创建一个rs客户端。您可以参考上面的RSClient。