gpt4 book ai didi

java - Eclipse - GWT - Java - MySQL - 如何正确捕获异常

转载 作者:行者123 更新时间:2023-11-28 22:42:39 24 4
gpt4 key购买 nike

我终于完成了我的应用程序(Eclipse、GWT、Java、MySQL、Tomcat)并将其上传到服务器上(我让其他人将应用程序上传到服务器上)。但是,服务器安装似乎有问题,我的代码没有发回任何错误。

例如:当创建一个新帐户时,会显示以下消息“您的帐户已创建。请联系领导将青年成员关联到该帐户。”但是数据库没有更新。看来我没有正确捕获异常。

我的代码是:

客户端调用:

AsyncCallback<User> callback = new CreationHandler<User>();
rpc.createUser(textBoxAccount.getText(), textBoxPassword.getText(), null, null, null, callback);

服务器端:

public User createUser(String userName, String pass, String level, String pack, java.sql.Date archived) {
User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
String pw_hash = BCrypt.hashpw(pass, BCrypt.gensalt());
try {
ps = conn.prepareStatement(
"INSERT INTO at_accounts (acc_email_address, acc_password, acc_enabled) " +
"VALUES (?, ?, ?)");
ps.setString(1, userName);
ps.setString(2, pw_hash);
ps.setString(3, "1");
ps.executeUpdate();
}
catch (SQLException e) {
//do stuff on fail
System.out.println("SQLException createUser 1.");
e.printStackTrace();
user = null;
}
finally {
if (result != null) {
try {
result.close();
}
catch (SQLException e) {
System.out.println("SQLException createUser 2.");
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
}
catch (SQLException e) {
System.out.println("SQLException createUser 3.");
e.printStackTrace();
}
}
}
return user;
}

客户端:

class CreationHandler<T> implements AsyncCallback<User> {
//Create the account.
public void onFailure(Throwable ex) {
Window.alert("RPC call failed - CreationHandler - Notify Administrator.");
}
public void onSuccess(User result) {
Window.alert("Your account has been created. Please contact a leader to associate youth members to it.");

}
}

如有任何帮助,我们将不胜感激。

问候,

格林

嗨,乔克,

请问是这个意思吗?

public User createUser(String userName, String pass, String level, String pack, java.sql.Date archived) {
User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
String pw_hash = BCrypt.hashpw(pass, BCrypt.gensalt());
try {
ps = conn.prepareStatement(
"INSERT INTO at_accounts (acc_email_address, acc_password, acc_enabled) " +
"VALUES (?, ?, ?)");
ps.setString(1, userName);
ps.setString(2, pw_hash);
ps.setString(3, "1");
ps.executeUpdate();
}
catch (SQLException e) {
//do stuff on fail
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("SQLException createUser 1.");
e.printStackTrace();
user = null;
}
finally {
if (result != null) {
try {
result.close();
}
catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("SQLException createUser 2.");
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
}
catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("SQLException createUser 3.");
e.printStackTrace();
}
}
}

try {
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("SQLException createUser 4 - commit error.");
e.printStackTrace();
}
return user;
}

这是带有建议的错误处理的更新代码:

package org.AwardTracker.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import org.AwardTracker.client.BCrypt;

import org.AwardTracker.client.Account;
import org.AwardTracker.client.AccountAndCubs;
import org.AwardTracker.client.AccountCubAssociation;
import org.AwardTracker.client.AwardAward;
import org.AwardTracker.client.AwardDescription;
import org.AwardTracker.client.AwardStockDtls;
import org.AwardTracker.client.DBConnection;
import org.AwardTracker.client.SectionDetails;
import org.AwardTracker.client.Stock;
import org.AwardTracker.client.User;
import org.AwardTracker.client.ViewData;
import org.AwardTracker.client.YMATask;
import org.AwardTracker.client.YMAwards;
import org.AwardTracker.client.YMandAward;
import org.AwardTracker.client.YMAwardDetails;
import org.AwardTracker.client.YouthMember;
import org.AwardTracker.client.YouthMemberAwards;
import org.AwardTracker.client.YthMmbrSectDtls;

import org.AwardTracker.server.Base64Encode2;

public class MySQLConnection extends RemoteServiceServlet implements DBConnection {
//TODO
// •Use JNDI to bind the data source.
// •Close the connection as soon as its done in finally block.
// •Manage the connection in single class for whole application.
// •Initialise the data source at application start up single time.
// •Store the database configuration outside the JAVA code somewhere in properties file or web.xml.
// •Create an abstract class for AsyncCallback that will handle all the failures happened while performing any RPC calls.
// •Extend this abstract class for all RPC AsyncCallback but now you have to just provide implementation of onSuccess() only.
// •Don't handle any exception in service implementation just throw it to client or if handled then re-throw some meaning full exception back to client.
// •Add throws in all the methods for all the RemoteService interfaces whenever needed.

private static final long serialVersionUID = 1L;
private Connection conn = null;
private String url = "jdbc:mysql://localhost/awardtracker";
private String user = "awtrack";
private String pass = "************";

public MySQLConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
//NEVER catch exceptions like this

System.out.println("Error connecting to database - not good eh");
e.printStackTrace();
}
}

//Store and retrieve data used by Views within the application
//This allows us to securely pass parameters between Views.
private ViewData viewData = null;

public ViewData setViewData(String accountId, String accountLevel,
String ymId, String awId, String adGroup) {

viewData = new ViewData();

viewData.setaccountId(accountId);
viewData.setaccountLevel(accountLevel);
viewData.setymId(ymId);
viewData.setawId(awId);
viewData.setadGroup(adGroup);

return viewData;
}

public ViewData getViewData() {
return viewData;
}


public User authenticateUser(String accID, String userName, String pass, String level, String pack, Integer enabled, java.sql.Date archived) {

User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
String stored_hash = null;

try {
ps = conn.prepareStatement(
"SELECT * " +
"FROM at_accounts " +
"WHERE acc_email_address = ?");

ps.setString(1, userName);

result = ps.executeQuery();

while (result.next()) {
user = new User(result.getString(1), result.getString(2), result.getString(3), result.getString(4), result.getString(5), result.getInt(6), result.getDate(7));
stored_hash = result.getString(3);
}
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e2) {
System.out.println("Error rolling back transaction for authenticateUser.");
e2.printStackTrace();
}
System.out.println("SQLException in authenticateUser.");
e.printStackTrace();
}

if (stored_hash != null) {
if (BCrypt.checkpw(pass, stored_hash)) {
} else {
user = null;
}
}else{
user = null;
}

return user;
}

//Disable or enable Account
public User disableUser(String user, Integer enabled) {
PreparedStatement ps = null;

try {
ps = conn.prepareStatement(
"UPDATE at_accounts " +
"SET acc_enabled=? " +
"WHERE acc_email_address=?");

ps.setInt(1, enabled);
ps.setString(2, user);
ps.executeUpdate();
conn.commit();
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e2) {
System.out.println("Error rolling back transaction for createUser.");
e2.printStackTrace();
}
System.out.println("SQLException in createUser.");
e.printStackTrace();
}

return null;
}

public User duplicateUser(String userName, String pass, String level, String pack, java.sql.Date archived) {
User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(
"SELECT * " +
"FROM at_accounts " +
"WHERE acc_email_address = ?");

ps.setString(1, userName);

result = ps.executeQuery();
while (result.next()) {
user = new User(null, result.getString(2), null, null, null, null, null);
}
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e2) {
System.out.println("Error rolling back transaction for duplicateUser.");
e2.printStackTrace();
}
System.out.println("SQLException in duplicateUser.");
e.printStackTrace();
}
return user;
}

public User createUser(String userName, String pass, String level, String pack, java.sql.Date archived) {
PreparedStatement ps = null;
String pw_hash = BCrypt.hashpw(pass, BCrypt.gensalt());
try {
ps = conn.prepareStatement(
"INSERT INTO at_accounts (acc_email_address, acc_password, acc_enabled) " +
"VALUES (?, ?, ?)");
ps.setString(1, userName);
ps.setString(2, pw_hash);
ps.setString(3, "1");
ps.executeUpdate();
conn.commit();
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e2) {
System.out.println("Error rolling back transaction for createUser.");
e2.printStackTrace();
}
System.out.println("SQLException in createUser.");
e.printStackTrace();
}

return null;
}

最佳答案

要记住的要点:

  • 使用JNDI绑定(bind)数据源。
  • finally block 中完成后立即关闭连接。
  • 在单个类中管理整个应用程序的连接。
  • 在应用程序启动时初始化数据源。
  • 将数据库配置存储在 JAVA 代码之外的属性文件或 web.xml 中。

我已经分享了 ConnectionUtil 类的示例代码,其唯一目的是使用 JNDI 查找 管理单个类中的连接,它可以记录有多少连接申请中几点开放?

请看下面的帖子:


GWT - how to catch an exception correctly?

  • AsyncCallback 创建一个抽象类,它将处理执行任何 RPC 调用时发生的所有失败。
  • 为所有 RPC AsyncCallback 扩展此抽象类,但现在您只需提供 onSuccess() 的实现即可。
  • 不处理服务植入中的任何异常,只是将其抛给客户端,或者如果已处理,则将一些有意义的完整异常重新抛回给客户端。
  • 在需要时为所有 RemoteService 接口(interface)的所有方法添加 throws

示例代码:

// single class to handle all the AsyncCallback failure
public abstract class MyAsyncCallback<T> implements AsyncCallback<T> {

@Override
public void onFailure(Throwable caught) {
// all the failure are catched here
// prompt user if needed
// on failure message goes to here
// send the failure message back to server for logging
}

}

// do it for all the RPC AsyncCallback
public class CreationHandler<T> extends MyAsyncCallback<T> {
//Create the account.
public void onSuccess(T result) {
// on success message goes to here
}
}

// use in this way
AsyncCallback<User> callback = new CreationHandler<User>();

关于java - Eclipse - GWT - Java - MySQL - 如何正确捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23587875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com