简体   繁体   中英

Invoking JAX-RS service from a servlet

I'm currently working on a java web application using Eclipse. 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.

My issue is how to pass parameters from the servlet to the web service, and then invoke the service from the servlet.

I have tried methods using context and Httpconnections to do this but neither seemed to have work.

Any help or advice would be greatly appreciated!

My code for the 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:

@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

first, you have to build a rs client

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

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

and last specify the http method, take get for example

Type returnObj = builder.get(Type); 

once builder.get(Type) is executed, it will return an object whose type is "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. https://jersey.java.net/documentation/latest/client.html


I'll give you a simple runnable example

my pom dependency

<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

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. You should see helloworld on console.

What you need to do is, make a rs client in your servlet. You can refer to RSClient above.

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