我正在创建一个需要用户身份验证的应用程序。我尝试登录时遇到一个问题。当我输入正确的用户名和密码时,会调用onSuccess方法。但是当我键入错误的字段或空字段时,则不会调用onFailure()方法。
我真的想知道为什么会这样。因为当用户名或密码不正确时,我不想显示某种对话框。
这是ClickHandler,它从字段中获取用户名和密码:
loginButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String username = usernameBox.getText();
String password = passwordBox.getText();
performUserConnection(username, password);
}
});
这是执行用户连接的方法,正如我所说,如果我有正确的用户名/密码,它就可以工作。它显示我的警报消息,但如果它不正确,则不会显示任何警告消息。
private static void performUserConnection(String username, String password) {
DBConnectionAsync rpcService = (DBConnectionAsync) GWT.create(DBConnection.class);
ServiceDefTarget target = (ServiceDefTarget) rpcService;
String moduleRelativeURL = GWT.getModuleBaseURL() + "DBConnectionImpl";
target.setServiceEntryPoint(moduleRelativeURL);
rpcService.authenticateUser(username, password, new AsyncCallback<User>() {
@Override
public void onSuccess(User user) {
Window.alert("TRALALA. Username: " + user.getUsername());
}
@Override
public void onFailure(Throwable caught) {
Window.alert("LALALALAL");
// DialogBox dialogBox = createDialogBox();
// dialogBox.setGlassEnabled(true);
// dialogBox.setAnimationEnabled(true);
// dialogBox.center();
// dialogBox.show();
}
});
}
更新服务器部分。
public class DBConnectionImpl extends RemoteServiceServlet implements DBConnection {
private static final long serialVersionUID = 1L;
private String URL = new String("jdbc:mysql://localhost:3306");
private String user = "root";
private String pass = "andrei";
private String schema = "administrare_bloc";
public DBConnectionImpl() {
}
private Connection getConnection() throws Exception {
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", pass);
props.setProperty("zeroDateTimeBehavior", "convertToNull");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL + "/" + schema, props);
return conn;
}
@Override
public User authenticateUser(String username, String password) throws Exception {
User returnUser = null;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
try {
String q = "select * from users where username=? and password=?";
stmt = conn.prepareStatement(q);
stmt.setString(1, username);
stmt.setString(2, password);
rs = stmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String user = rs.getString("username");
String pass = rs.getString("password");
String type = rs.getString("type");
returnUser = new User(id, user, pass, type);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
rs.close();
stmt.close();
conn.close();
}
return returnUser;
}
}
提前致谢
答案 0 :(得分:4)
只有在服务器上抛出异常时,才会调用onFailure方法。现在,如果没有找到用户,您只需返回一个空对象。