2012-11-15 19 views
9

Attualmente sto utilizzando Jersey per restituire JSON. Come restituire invece JSONP? Per esempio, il mio attuale metodo RESTful è:Restituzione di JSONP da Jersey

@GET 
@Produces(MediaType.APPLICATION_JSON) 
public List<Order> getOrders() { 
    return OrderRepository.getOrders(); 
} 

vorrei distribuire su Tomcat (non vogliono richiedere l'uso di GlassFish). Le mie uniche dipendenze su Jersey sono:

<dependency> 
     <groupId>com.sun.jersey</groupId> 
     <artifactId>jersey-json</artifactId> 
     <version>1.9.1</version> 
    </dependency> 

    <dependency> 
     <groupId>com.sun.jersey</groupId> 
     <artifactId>jersey-server</artifactId> 
     <version>1.9.1</version> 
    </dependency> 

Quali ulteriori dipendenze sono necessarie? Come cambierà il codice?

Grazie.
Naresh

risposta

9

Date un'occhiata al JSONP esempio (in particolare la risorsa ChangeList) a Jersey (è possibile scaricare l'intero progetto here).

Quello che fondamentalmente dovete fare è qualcosa di simile:

@GET 
@Produces(MediaType.APPLICATION_JSON) 
public JSONWithPadding getOrders() { 
    return new JSONWithPadding(new GenericEntity<List<Order>>(OrderRepository.getOrders()){}); 
} 
+0

Che ha funzionato come un fascino! Grazie! – Naresh

+4

È necessario produrre "application/javascript" e potenzialmente aggiungere il parametro callback come nell'esempio. –

6

E 'importante modificare la risposta corretta, come @s_t_e_v_e dice. Dovrebbe essere qualcosa del genere:

@GET 
@Produces({"application/javascript"}) 
public JSONWithPadding getOrdersJSonP(@QueryParam("callback") String callback) { 
    List<Order> orderList = OrderRepository.getOrders(); 
    return new JSONWithPadding(new GenericEntity<List<Order>>(orderList){}, 
       callback); 
    }