Returning an Integer from RESTful web services met

2020-04-21 03:26发布

问题:

Am new to RESTful web services. I wrote a web service method and am currently returning an XML by using @Produces(MediaType.TEXT_XML). But the requirement is that my web service method must return an Integer instead of XML. How can I achieve this? kindly help me with this. Below is the method I wrote.

@Path("{type}/{token}")
@GET
@Produces(MediaType.TEXT_XML)
public String setToken(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("type") String type, @PathParam("token") String token) throws ServletException, IOException {
    String value=token;
    if(request==null){
        System.out.println("Request null");
    }

    System.out.println("Token: " + value);
    System.out.println("AnumLotnum: " + type);

    if(request!=null){
        request.setAttribute("param", value);
        request.getRequestDispatcher("/dummy").include(request, response);
    }

    String id=request.getAttribute("ID").toString();
    return "<token>"+ "<value>"+id+"</value>" + "</token>";
}

回答1:

Use @Produces(MediaType.TEXT_PLAIN) instead of @Produces(MediaType.TEXT_XML)

It will be text as you are using RESTful Webservices which is a pure HTTP implementation(Hyper TEXT Transfer Protocol).

To get an integer you can either cast at Client side manually.

Actually you have two options you may either return String or int, both will do. By returning int, a smart Client like Jersey Http client will automatically cast the String to int for you.

Example

  @Path("{type}/{token}")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public int setToken(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("type") String type, @PathParam("token") String token) throws ServletException, IOException {
return 1;     
}