Request Dispatcher causing $.get of jQuery to alert the text of the page Request Dispatcher causing $.get of jQuery to alert the text of the page ajax ajax

Request Dispatcher causing $.get of jQuery to alert the text of the page


You want to write some information from within your servlet back to the client.Your serlvet could look like this:

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

And that's all there is (obviously wiring the servlet to your URL in web.xml). Your $.get() should see whatever you write into the writer.

Note that both what's sent (in Java) and what's received (in Javascript) are TEXT strings. You're responsible to convert your data to readable JSON on the Java side, and to interpret the text as JSON on the Javascript side. The latter can be done like this:

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


In this case the final response is coming from test.jsp because you have forwarded the request to test.jsp inside that Test_Controller.html. If you want to print that json data to test.jsp then you don't need to forward that request to test.jsp page.Otherwise you can also create that json file inside test.jsp using scriplet tag like:

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

Happy Coding!!!


Get the object in test.jsp .

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

Javascipt USE $.getJSON instead of $.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");  }  );});