Java 在Eclipse中,通过Jquery向Servlet发送Ajax查询很困难
我在Eclipse中的.jsp文件中运行了以下jQuery语句,该文件位于WebContent/public目录中:Java 在Eclipse中,通过Jquery向Servlet发送Ajax查询很困难,java,jquery,ajax,servlets,Java,Jquery,Ajax,Servlets,我在Eclipse中的.jsp文件中运行了以下jQuery语句,该文件位于WebContent/public目录中: $(document).ready(function(){ $('#login').click(function(){ $('#display').html('Logging in...'); var username = $('#username').val(); var p
$(document).ready(function(){
$('#login').click(function(){
$('#display').html('Logging in...');
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url : '/AuthenticationServlet',
type : 'POST',
dataType : 'text',
data : {'username' : username, 'password' : password},
success : function(data) {
$('#display').html('');
if(data != "SUCCESS"){
//TODO create an element to display validity
$('#display').html('Invalid Username/Password combination');
}else if (data == "SUCCESS"){
$('#username').val('');
$('#password').val('');
$('#display').html('Success!');
}
else{
$('#display').html('Something has gone horribly wrong.');
}
}
});
return false;
});
});
我在src/authentication目录中有我的servlet AuthenticationServlet,它的编写如下:
/**
* Servlet implementation class AuthenticationServlet
*/
@WebServlet("/AuthenticationServlet/*")
public class AuthenticationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public AuthenticationServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
* This method gets the username and password from the jsp file, then proceeds to pass them to
* the authentication helper for validation.
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get the parameters from the request
String username = request.getParameter("username");
String password = request.getParameter("password");
//verify the login/password combination is correct
boolean authenticated = AuthenticationHelper.verifyUser(username, password);
if(authenticated){
response.getWriter().write("SUCCESS");
}
else{
response.getWriter().write("FAILURE");
}
}
}
问题是,在输入有效的用户名和密码组合时,JSP中我的“display”元素只会更改为“Logging in”,根本不会更改,这表示jquery不再执行任何代码,而这些代码最终会将元素更改为其他内容(无论是空的还是其他任何字符串)。我做错了什么?我的URL不正确吗 因为您希望以
username=usernameValue&password=passwordValu
e的形式发送请求。因此,修改url
和data
如下:
url : 'AuthenticationServlet', // Remove /, it will skip the context path.
data : {username : username, password : password}, // Remove quotation.
尝试添加
error:function(){alert('error');}
,查看是否出现此警报,如果是,请在删除数据类型后重试:“text”
。这会给出404,至少在本地主机上是这样