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....

3
  • yes the return of arraylist is correct. Commented Apr 18, 2014 at 9:32
  • from where do you send your request? And where do you want the response? Commented Apr 18, 2014 at 9:34
  • The request will be from different Java application on different web app and the response will be getting from the spring controller of another different web app. Commented Apr 18, 2014 at 10:30

4 Answers 4

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

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!!

13 Comments

Hi San krish ! But I have to get the response from a java code which I have already posted. I am getting
Actually I need to retrieve the List<String> from response in my java code.
You are forwarding the list from controller right? . And where you are forwarding the result to?
@user2138790 So the assumption here is that the response from your controller is processed by a JSP View, is that correct?
Exactly what @TarunGupta says
|
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

4 Comments

"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.
The content headers are set while sending the request from a plain java client to a web service. Here is an Example. Here is an example of how to consume (writing the client side code for) a web-service using Spring framework hope it helps.
Hi Hirein, in the example that I posted returning List<Sting> should also work fine.
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.