Reputation: 225
I am developing a webapplication based on JSP. I have a servlet class :
package managesystem;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
public class getUsernamesServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse resp){
List<String> usernamesList = StudentManager.findAllUsernames();
req.setAttribute("usernames", new Gson().toJson(usernamesList));
}
}
My question is as follows : How do I check with Ajax if a usernames is still available (if it isn't present in the list) ? How do I get the JSON information that the servlet writes to the request, in for example register.jsp using Ajax ?
Kind regards,
h4
Upvotes: 3
Views: 9428
Reputation: 1108782
You need to write it to the response body instead of setting it as a request attribute.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(usernamesList));
This way the Ajax request on this servlet retrieves a JSON response which can then be traversed the usual way using JavaScript.
That said, if your sole purpose is to check if the username is available, then you can also approach this a bit differently. Instead of pumping the entire list of all user names over the network and doing the checking job in the JavaScript side, you could also just send the entered username as a request parameter to the servlet and let the DB do the checking job and return just a boolean true
or false
whether the usename is available. For example,
String username = request.getParameter("username");
boolean usernameAvailable = studentService.usernameAvailable(username);
Map<String, Object> data = new HashMap<String, Object>();
data.put("usernameAvailable", usernameAvailable);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data));
with
$.get('someservlet', { 'username': username }, function(data) {
if (!data.usernameAvailable) {
$('#somemessage').text('Username is not available, please choose another').show();
}
});
That's more bandwidth-efficient and less prone for leaking sensitive information.
Upvotes: 5