bourbaki4481472 bourbaki4481472 - 4 months ago 16
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 (


The following is an excerpt from the hello.jsp:

<script src=""></script>
$.get('hello', function(data) {

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


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

Except from

public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String data = "Hello World from doGet()!";

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
to javascript's
, but instead
is displayed in the
div. Any advice?


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.