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?