You can use jQuery for this. In jQuery you have the great form plugin which unobtrusively changes an existing form into an ajaxform.
HTML (in JSP):
<form id="myform" action="myservlet" method="post">
<input type="text" name="foo">
<input type="submit">
</form>
<div id="message">${message}</div>
JS ((in)directly in JSP):
$('#myform').ajaxForm({
success: function(message) { $('#message').text(message); }
});
Java ((in)directly in doPost()
method of the Servlet behind myservlet
):
String foo = request.getParameter("foo");
String message = "You entered 'bar': " + ("bar".equals(foo) ? "yes" : "no");
if ("XMLHttpRequest".equals(request.getHeader("x-requested-with"))) {
// Ajax request.
response.getWriter().write(message);
} else {
// Normal request.
request.setAttribute("message", message);
request.getRequestDispatcher("page.jsp").forward(request, response);
}
If you want to get some steps further, you can use Gson in Servlet to convert complete Java objects to Javascript object notation (JSON). This way you can access the data the javabean-like way in Javascript.