2014-11-17 11 views
9

ad esempio:

ho un js come:

$.get('Test_Controller.html',function(response){ 
    alert(response); 
}); 

e nel mio Test_Controller.html servlet ho:

request.setAttribute("test","testData"); 
    RequestDispatcher requestDispatcher = 
    request.getRequestDispatcher("/test.jsp"); 
    requestDispatcher.forward(request,response); 

domanda è:

perché è che il response sarà sempre all'erta il contenuto del testo del test.jsp e non il JSON che ho attraversato il getWriter()

EDIT:

ho bisogno di ottenere il:

TestData testData = new TestData(); 
    request.setAttribute("test",testData); 

usando jQuery $ .get() in modo che il la pagina non verrà ricaricata ma, sfortunatamente, quando non l'ho fatto, l'oggetto della mia risposta sembra essere nullo e quando invio e inoltro, quando avviso la risposta, avverte il testo della pagina.

+0

Perché si preparare una risposta poi l'ora di un'altra pagina? La risposta non è pronta dopo che hai scritto il json in esso? Se è necessario chiamare anche 'test.jsp', perché non generare il json da dentro 'test.jsp'? – geert3

+0

Si prega di verificare la mia domanda aggiornata per chiarimenti.grazie – Yaje

+0

dopo la tua modifica, non vedo più alcuna menzione di JSON. Stai scrivendo il JSON direttamente da JSP? Si prega di precisare. Ad ogni modo per ottenere il file request.setAttribute(), non puoi passarlo come parametri url? Ad esempio '$ .get ('Test_Controller.html? Test = testData')' – geert3

risposta

6

Si desidera scrivere alcune informazioni dall'interno del servlet al client. tuo serlvet potrebbe essere la seguente:

@Override 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{ 
    response.setContentType("application/json"); 
    Writer w = response.getWriter(); 
    w.append("... your json here ...."); 
} 

E questo è tutto quello che c'è (ovviamente il cablaggio del servlet per l'URL in web.xml). Il tuo $.get() dovrebbe vedere tutto ciò che scrivi nello scrittore.

Si noti che sia ciò che viene inviato (in Java) sia quello ricevuto (in Javascript) sono stringhe TEXT. Sei responsabile di convertire i tuoi dati in JSON leggibile sul lato Java e di interpretare il testo come JSON sul lato Javascript. Quest'ultimo può essere fatto in questo modo:

$.get(....., function(data) { 
    try { 
     // convert the text to JSON 
     data = jQuery.parseJSON(data); 
    } catch (e) { 
     alert("Problem reading data: "+e); 
    } 
    ... use the JSON data ... 
} 
+0

quando si usa 'w.append()' posso inserire un oggetto all'interno di 'append()'? per esempio un 'testData' che contiene molti attributi? – Yaje

+0

No, lo scrittore richiede 'String's (' CharSequence's per essere precisi). Ci sono probabilmente molte classi di utitlity là fuori (o anche in Java API) per convertire qualunque tipo di nome/valore tu abbia (HashMap? Properties?) In JSON leggibile. – geert3

+0

vedere i miei chiarimenti nella risposta principale – geert3

2

In questo caso la risposta finale proviene da test.jsp perché avete inoltrato la richiesta al test.jsp dentro quel Test_Controller.html. Se si desidera stampare tali dati json su test.jsp, non è necessario inoltrare tale richiesta alla pagina test.jsp.Inoltre è possibile creare tale file json all'interno di test.jsp utilizzando tag scriplet come:

<% 
request.setAttribute("test","testData"); 
response.setContentType("application/json"); 
response.setCharacterEncoding("UTF-8"); 
String json = new Gson().toJson(test); 
response.getWriter().write(json); 
%> 

Happy Coding !!!

+0

Ciao, grazie per il chiarimento sulla risposta finale .. c'è un modo per passare l'attributo di richiesta alla risposta di $ .get() senza usare JSON e dispatcher? – Yaje

+0

Yes.Inside Test_Controller.html possiamo scrivere: io suggerisco di utilizzare pagina JSP invece di usare html.In questo caso puoi scrivere all'interno di Test_Controller.jsp: <% TestData testData = new TestData(); out.println (testData); %> –

+1

Giusto per chiarire ... il 'Test_Contoller.html' è un servlet mappato. una classe .java. – Yaje

-1

Recupera l'oggetto in test.jsp.

<% 
    TestData testData = (TestData) request.getAttribute("test"); 
    String testDataString = new GSON().toJson(testData); 
    out.println(testDataString); 
%> 

Javascipt USO $ GetJSON invece di $ .get

$.getJSON('Test_Controller.html',function(responseJSON){ 
    alert(responseJSON); 
var testData = responseJSON;// Then you can accesss your class values. 

$.each(testData,function(key,value){ 
     alert("Key:-"+key+": Value:-"+value"); 
    } ); 

}); 
Problemi correlati