bourbaki4481472 bourbaki4481472 - 1 month ago 8
Java Question

Passing a value from servlet doGet() to javascript's $.get() returning whole HTML instead

My work necessitates working with Java logic and Javascript. So, now I am trying to pass a value to javascript once a doGet() of a servlet is executed. Somehow, instead of some Java string, javascript displays the whole HTML String as the value (

"<html>...<body>....</body>...</html>"
).

The following is an excerpt from the hello.jsp:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.get('hello', function(data) {
$('#data').text(data);
});
</script>

<body>
<div id="input">
<form action="hello" method="get">
<p><input type="text" name="query" value="${messages.query}"><input type="submit" value="Go!"></p>
<hr>
</form>

</div>

<div id="data"></div>
</body>


Except from HelloController.java:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


String data = "Hello World from doGet()!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);

request.getRequestDispatcher("/WEB-INF/pages/hello.jsp").forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
...
*/
}

}


So, once doGet() is executed, I want
"Hello World from doGet()"
to be passed back as
data
to javascript's
$.get()
, but instead
"<html>...<body>....</body>...</html>"
is displayed in the
data
div. Any advice?

Answer

Look at what your doGet is doing.

String data = "Hello World from doGet()!"; // creates a String
response.setContentType("text/plain"); // sets the content type
response.setCharacterEncoding("UTF-8"); // sets the encoding
response.getWriter().write(data); // writes the value of the String to the response

and finally

request.getRequestDispatcher("/WEB-INF/pages/hello.jsp").forward(request, response);

What does this do? The javadoc states

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response.

A JSP is a Servlet. So when you forward to that JSP, it is rendered and the generated HTML gets written to the HTTP response. If you don't want that, get rid of it.