I have just read some articles on Google about basics of ajax. I want an ajax program for user name validation in my java web application. I searched a lot on internet but I didn't get any sample program of ajax and its server side coding in java. All sample program have server side coding for php or asp. I am not getting how to send response from java servlet to ajax. Can you please provide me with some example or program for how to use ajax in java?
Asked
Active
Viewed 5,450 times
3 Answers
2
I am not getting how to send response from java servlet to ajax.
Just write it to the response.
response.getWriter().write(result);
Here's a more concrete kickoff example:
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("#username").change(function() {
$.get("validateUsernameServlet", $(this).serialize(), function(data) {
if (!data.valid) {
$("#username_message").text("Duplicate username, choose another");
}
});
});
});
</script>
</head>
<body>
<form action="register" method="post">
<input type="text" id="username" name="username" />
<span id="username_message"></span>
...
</form>
</body>
Here's how the doGet()
of the servlet can look like:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
boolean valid = yourUserService.isValidUsername(username);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("{\"valid\":" + valid + "}");
}
See also:
-
The direct use of a servlet works nicely in small cases like this example. When you need to return more complex results and when you have several related services, perhaps using GET and POST and DELETE, then there's lots more code to write. Becomes much easier to use JAX/RS. – djna Mar 03 '12 at 06:01
1

Java
- 2,451
- 10
- 48
- 85
-
is it neccesary that i need to create servlet for server side validation? Can i do it using jsp pages? – adesh Feb 29 '12 at 13:49
1
You want to write what is usually termed a RESTful service.
There's a standard Java approach to doing this: JAX/RS. You write some Java and annotate it to indicate what Ajax service it provides. Very easy to do.
The Apache Wink project is a freely downlaodable an implementation.
I have a series of articles on my blog about writing and testing such services

djna
- 54,992
- 14
- 74
- 117
-
-
Ajax usually means that some Javascript in the Browser calls a service provided by a Java server. A JSP might have delivered the original page to the Browser, but the service itself is implemented in Java - I suggest using JAX/RS – djna Feb 29 '12 at 16:29