2

I am new to this kind of coding where in I have to send a collection of String i.e., List from a Spring controller of different web app. So my questions are

  1. How should I return the Response which consists of List from a controller? Does the below code works fine? Below is my controller code where I will be returning List<String>.

    @RequestMapping(value = "getMyBookingsXmlList", method = RequestMethod.GET)
    public @ResponseBody List<String> getMyBookingsXmlList() {
        return mbXmlImpl.getMyBookingsDetailsXmlList();
    }
    
  2. In the client side how should I have to retrieve the List<String> which was sent from the above controller method ? Below is the code which I am trying to do but I have no clue as of how to do.

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("URL");
    HttpResponse httpResponse = httpclient.execute(httpGet);
    InputStream is = httpResponse.getEntity().getContent();
    StringBuffer buffer = new StringBuffer();
    byte [] b = new byte [1024];
    for (int n ; (n = is.read(b)) != -1 ;)
        buffer.append(new String(b, 0, n));
    

After this I don't have a clue what to do....

hpopiolkiewicz
  • 3,281
  • 4
  • 24
  • 36
Hirein Nag
  • 21
  • 1
  • 2
  • 5

4 Answers4

1

The easiest solution to consume your Rest service with a java client is to use Spring RestTemplate. I would suggest you wrap your List<String> in another class and return that from your controller:

public class BookingList  {
    private List<String> booking;
    // getters and setters
}

With this your client code will be very simple:

BookingList bookingList = restTemplate.getForObject("http://yoururl", BookingList.class, Collections.emptyMap() ) ;

If you want to continue to keep List<String> as return type, then the client code will look like this:

    ResponseEntity<List<String>> bookingListEntity = restTemplate.exchange("http://yoururl", HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>() {}, Collections.emptyMap() ) ;
    if (bookingListEntity.getStatusCode() == HttpStatus.OK) {
        List<String> bookingList = bookingListEntity.getBody();
    }
Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125
0

If you are using the jstl you can iterate it through the for-each as

 <c:forEach items="${Name_of_RequestAttribute}" var="ite">
  <option value="${ite.Name_of_RequestAttribute}">${ite.Name_of_RequestAttribute}</option>
 </c:forEach>

Hope this helps!!

Santhosh
  • 8,181
  • 4
  • 29
  • 56
  • Hi San krish ! But I have to get the response from a java code which I have already posted. I am getting – Hirein Nag Apr 18 '14 at 10:27
  • Actually I need to retrieve the List from response in my java code. – Hirein Nag Apr 18 '14 at 10:32
  • You are forwarding the `list` from controller right? . And where you are forwarding the result to? – Santhosh Apr 18 '14 at 10:33
  • 1
    @user2138790 So the assumption here is that the response from your controller is processed by a JSP View, is that correct? – Tarun Gupta Apr 18 '14 at 10:43
  • Exactly what @TarunGupta says – Santhosh Apr 18 '14 at 10:45
  • @Tarun Gupta the response here is used by a method in other java web app to be specific. – Hirein Nag Apr 18 '14 at 11:26
  • san krish I will be returning the List to a java method(present in a different webapp). I know this requirement is little weirs but its a requirement. – Hirein Nag Apr 18 '14 at 11:29
  • I think the better way would be to use web-service type of message exchange between the two web applications. – Tarun Gupta Apr 18 '14 at 11:36
  • Tarun actually the requirement was to use the existing controller rather than implementing the WebServices. – Hirein Nag Apr 18 '14 at 11:39
  • Tarun Gupta Just correct me if I am wrong. In the spring controller I have to send the JSON which is having List. And in my java method where I am calling this controller, I have to get the JSON from the response. Am I right Tarun ? – Hirein Nag Apr 18 '14 at 11:42
  • Guys I am waiting for your replies.. :) – Hirein Nag Apr 18 '14 at 12:24
  • @HireinNag If your 'already existing application' runs on a different Web container then yes its best to use JSON type of interaction. If you are just trying to extend an existing application and the existing controller class runs in same web container (packaged in the same 'war' file) then you can wire (or extend from) the existing controller class and use the method directly. – Tarun Gupta Apr 19 '14 at 06:42
  • @Tarun Gupta yes the application is running on two different web container. The suggestion which you have suggest like using the concept of JSON looks reasonable. I will be following that. I will let you know if I face any difficulties. I hope you will be available ti guide me.. :) – Hirein Nag Apr 21 '14 at 06:03
0

I think a better way would be to have a RESTFul webservice in your application that provides the BookingXml.

In case you are planning to expose your Existing Controller code as a Rest Webservice, you could use RestTemplate as explained in this example to make the web service calls.

Other resources you can refer to : http://java.dzone.com/articles/how-use-spring-resttemplate-0 http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch18s03.html

To be specific, in your case you could use this code example :

Controller :

@Controller
@RequestMapping("/help")
public class HelpController {

    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(HelpController.class);

    @RequestMapping("/method")
    public @ResponseBody String[] greeting() {
        return new String[] { "Hello", "world" };
    }
}

Client Code :

public class Client {

    public static void main(final String[] args) {
        final RestTemplate restTemplate = new RestTemplate();
        try {

            final String[] data = restTemplate.getForObject("http://localhost:8080/appname/help/method",
                    String[].class);
            System.out.println(Arrays.toString(data));
        }
        catch (final Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

In case authentication is needed there are 2 ways to pass user credentials when using RestTemplate :

  1. Create your RestTemplate object using this example :

    HttpClient client = new HttpClient();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("your_user","your_password");
    client.getState().setCredentials(new AuthScope("thehost", 9090, AuthScope.ANY_REALM), credentials);
    CommonsClientHttpRequestFactory commons = new CommonsClientHttpRequestFactory(client);
    RestTemplate template = new RestTemplate(commons);
    
  2. Or same can be done using Spring configuraitons as mentioned in this answer : https://stackoverflow.com/a/9067922/1898397

Community
  • 1
  • 1
Tarun Gupta
  • 1,629
  • 1
  • 22
  • 39
  • "In your java client you can set the content headers 'application/json". Can you explain this in terms of coding ? I know this is annoying but this is how it is. – Hirein Nag Apr 21 '14 at 06:45
  • The content headers are set while sending the request from a plain java client to a web service. [Here](http://stackoverflow.com/a/6443283/1898397) is an Example. [Here](https://spring.io/guides/gs/consuming-rest/) is an example of how to consume (writing the client side code for) a web-service using Spring framework hope it helps. – Tarun Gupta Apr 21 '14 at 07:45
  • Hi Hirein, in the example that I posted returning List should also work fine. – Tarun Gupta Apr 21 '14 at 08:24
  • I followed the above code. But the problem here is I need to send username, password along with the request since we have interceptors in the server code. How can I do that. – Hirein Nag Apr 22 '14 at 06:39
0

How about this solution?

...
ResponseEntity<MyObject[]> response = 
restTemplate.getForEntity(uribuilder.build().encode().toUri(), 
MyObject[].class);
return Arrays.asList(response.getBody());

Where MyObject can be anything, even String.

NoraT
  • 71
  • 1
  • 4