Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

for example :

i have a js like :

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

and in my Test_Controller.html servlet i have :

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

Question is :

why is that the response will always alert the text content of the test.jsp and not the JSON that i passed through the getWriter()

EDIT :

I need to get the :

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

using jQuery's $.get() so the page won't reload, but unfortunately when i didn't do dispatch my response object seems to be null and when i do dispatch and forward, when i alert the response it alerts the text of the page.

like image 351
Yaje Avatar asked Nov 17 '14 09:11

Yaje


2 Answers

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

@Override
protected 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 ...
}
like image 149
geert3 Avatar answered Nov 02 '22 01:11

geert3


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

like image 39
Debanjan Sharma Avatar answered Nov 01 '22 23:11

Debanjan Sharma