为什么JAVA表单信息拒绝更新?

问题描述 投票:0回答:1

当我在表单中插入数据并提交时,我收到了我刚刚更新的信息,并且消息“用户更新成功!”也显示在浏览器上,但是当我检查我的数据库时,我发现相同的信息我之前保持不变,没有任何变化,并且控制台上弹出消息“没有用户更新”。

我尝试检查我的数据库字段和 servlet,但仍然找不到问题。 这是我修改表单时发生的情况:

(ID 7 NOM doe PRENOM jhon 年龄 25 密码 jhon123 电子邮件 [email protected] IDROLE 2 用户更新成功!)

请问问题出在哪里?

这是我的 servlet 代码:

`protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String idutilisateurStr = request.getParameter("idutilisateur");
            int idutilisateur = -1; 
            if (idutilisateurStr != null && !idutilisateurStr.isEmpty()) {
                idutilisateur = Integer.parseInt(idutilisateurStr);
            }
            String nom = request.getParameter("nom");
            String prenom = request.getParameter("prenom");
            String ageint = request.getParameter("age");
            int age = Integer.parseInt(ageint);
            String email = request.getParameter("email");
            String mot_de_pass = request.getParameter("mot_de_pass");
            String idroleStr = request.getParameter("idrole");
            int idrole = Integer.parseInt(idroleStr);
            Role role = new Role(idrole);

            PrintWriter out = response.getWriter();
            Utilisateurs newUtilisateur = new Utilisateurs(idutilisateur, nom, prenom, age, email, mot_de_pass, role);
            
            System.out.println(newUtilisateur);
            out.print("ID " + idutilisateur + "<br> ");
            out.print("NAM " + nom + "<br> ");
            out.print("FIRST NAME " + prenom + " <br>");
            out.print("AGE " + age + "<br> ");
            out.print("PASSWORD " + mot_de_pass + "<br> ");
            out.print("EMAIL " + email + " <br>");
            out.print("IDROLE " + idrole + "<br> ");
            
            
            try {
                UserDAO.updateUser(newUtilisateur);
                response.getWriter().println("User updated successfully!");
            } catch (SQLException e) {
                e.printStackTrace();
                response.getWriter().println("Error updating user: " + e.getMessage());
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.getWriter().println("Invalid input format: " + e.getMessage());
        }
    }`

这是我的表格:

<form action = "UpdateServlet" method= "post">

idUtilisateur<input type="number" name="idutilisateur" value="${user.idUtilisateurs}" /><br>
Nom<input type="text" name = "nom" /><br>
Prenom<input type="text" name = "prenom" /><br>
Age<input type="number" name = "age" /><br>
Email<input type="email" name = "email" /><br>
Password<input type="password" name = "mot_de_pass" /><br>
Idrole 
<select name="idrole">
    <option value="1"> Admin <option>
    <option value="2">Client </option>
</select>


<input type="submit" value = "submit"/>

</form>

这是 DAO :

 private static final String Update_user = "UPDATE utilisateur SET 
 idutilisateur = ? ,nom = ? ,prenom=?  , age = ?,email = ? , mot_de_pass = ? , idrole = ?"
            + " WHERE  idutilisateur = ?";
    `public static void updateUser(Utilisateurs u) throws SQLException {
        try (Connection connection = Conx();
             PreparedStatement preparedStatement = connection.prepareStatement(Update_user)) {

            preparedStatement.setInt(1, u.getIdUtilisateurs());
            preparedStatement.setString(2, u.getNom());
            preparedStatement.setString(3, u.getPrenom());
            preparedStatement.setInt(4, u.getAge());
            preparedStatement.setString(5, u.getEmail());
            preparedStatement.setString(6, u.getPassword());
            preparedStatement.setInt(7, u.getRole().getIdRole());
            preparedStatement.setInt(8, u.getIdUtilisateurs());

            int rowsUpdated = preparedStatement.executeUpdate();

            if (rowsUpdated > 0) {
                connection.commit(); 
                System.out.println("User updated successfully!");
            } else {
                System.out.println("No user was updated.");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

这是编辑页面的链接:

<a href="UpdateForm.jsp?idutilisateur=${user.idUtilisateurs}">Edit</a>
java mysql servlets jakarta-ee dao
1个回答
0
投票

您在问题中没有发布足够的信息供我们做出诊断。但我可以给你一些提示和一些示例代码。

两个关键提示:

  • 您应该始终将数据库代码与 UI 分开编写和测试。
  • 从小事做起,一步一步来,一次添加一点代码,边做边编译和测试。

这里是一些使用 H2 数据库引擎的示例代码。

package work.basil.example.db;

import org.h2.jdbcx.JdbcDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.time.Instant;
import java.util.Collection;
import java.util.List;

public class FrenchUsers
{
    public static void main ( String[] args )
    {
        FrenchUsers app = new FrenchUsers ( );
        app.demo ( );
    }

    private void demo ( )
    {
        final DataSource dataSource = this.obtainDataSource ( );
        this.prepareDatabase ( dataSource );
        this.populateDatabase ( dataSource , this.sampleData ( ) );
        this.dumpToConsole ( dataSource );
        this.modifyOneRowByRoleCode ( dataSource );
        this.dumpToConsole ( dataSource );
    }

    private DataSource obtainDataSource ( )
    {
        org.h2.jdbcx.JdbcDataSource ds = new JdbcDataSource ( ); // An implementation of `javax.sql.DataSource` bundled with H2.
        ds.setURL ( "jdbc:h2:mem:ex_french_users_db;DB_CLOSE_DELAY=-1" );
        ds.setUser ( "scott" );
        ds.setPassword ( "tiger" );
        ds.setDescription ( "An example database showing how to modify a row per changes to an object." );
        return ds;
    }

    private void prepareDatabase ( DataSource dataSource )
    {
        System.out.println ( "INFO - Running `prepareDatabase` method. " + Instant.now ( ) );
        String sql = """
                CREATE TABLE IF NOT EXISTS utilisateur_
                (
                id_ INTEGER NOT NULL ,
                nom_ TEXT NOT NULL ,
                prenom_ TEXT NOT NULL ,
                age_ INTEGER NOT NULL ,
                email_ TEXT NOT NULL ,
                mot_de_passe_ TEXT NOT NULL ,
                role_code_ INTEGER NOT NULL ,
                CONSTRAINT id_ PRIMARY KEY ( id_ )
                )
                ;
                """;
        try (
                Connection conn = dataSource.getConnection ( ) ;
                Statement stmt = conn.createStatement ( ) ;
        )
        {
            stmt.executeUpdate ( sql );
        }
        catch ( SQLException e ) { e.printStackTrace ( ); }
    }

    private Collection < Utilisateur > sampleData ( )
    {
        System.out.println ( "INFO - Running `sampleData` method. " + Instant.now ( ) );
        return List.of (
                new Utilisateur ( 11 , "Abadie" , "Alice" , 49 , "[email protected]" , "123" , 7 ) ,
                new Utilisateur ( 12 , "Beaulieu" , "Bob" , 22 , "[email protected]" , "letmein" , 42 ) ,
                new Utilisateur ( 13 , "Charbonnier" , "Carol" , 72 , "[email protected]" , "password" , 7 ) );
    }

    private void populateDatabase ( final DataSource dataSource , final Collection < Utilisateur > originalData )
    {
        System.out.println ( "INFO - Running `populateDatabase` method. " + Instant.now ( ) );
        String sql = """
                INSERT INTO utilisateur_ ( id_ , nom_ , prenom_ , age_ , email_ , mot_de_passe_ ,role_code_ )
                VALUES ( ? , ? , ? , ? , ? , ? , ? )
                ;
                """;
        try (
                Connection conn = dataSource.getConnection ( ) ;
                PreparedStatement preparedStatement = conn.prepareStatement ( sql ) ;
        )
        {
            for ( Utilisateur utilisateur : originalData )
            {
                preparedStatement.setInt ( 1 , utilisateur.id ( ) );
                preparedStatement.setString ( 2 , utilisateur.nom ( ) );
                preparedStatement.setString ( 3 , utilisateur.prenom ( ) );
                preparedStatement.setInt ( 4 , utilisateur.age ( ) );
                preparedStatement.setString ( 5 , utilisateur.email ( ) );
                preparedStatement.setString ( 6 , utilisateur.motDePasse ( ) );
                preparedStatement.setInt ( 7 , utilisateur.roleCode ( ) );
                preparedStatement.executeUpdate ( );
            }
        }
        catch ( SQLException e ) { e.printStackTrace ( ); }
    }

    private void modifyOneRowByRoleCode ( final DataSource dataSource )
    {
        System.out.println ( "INFO - Running `modifyOneRowByRoleCode` method. " + Instant.now ( ) );
        Utilisateur utilisateur = this.modifiedUtilisateur ( );
        String sql = """
                UPDATE utilisateur_ 
                SET role_code_ = ?
                WHERE id_ = ? 
                ;
                """;
        try (
                Connection conn = dataSource.getConnection ( ) ;
                PreparedStatement preparedStatement = conn.prepareStatement ( sql ) ;
        )
        {
            preparedStatement.setInt ( 1 , utilisateur.roleCode ( ) );
            preparedStatement.setInt ( 2 , utilisateur.id ( ) );
            int countRowsAffected = preparedStatement.executeUpdate ( );
            System.out.println ( "DEBUG - SQL UPDATE affected " + countRowsAffected + " rows." );
        }
        catch ( SQLException e ) { e.printStackTrace ( ); }
    }

    private Utilisateur modifiedUtilisateur ( )
    {
        System.out.println ( "INFO - Running `modifiedUtilisateur` method. " + Instant.now ( ) );
        Utilisateur vieux = List.copyOf ( this.sampleData ( ) ).get ( 2 );
        Utilisateur nouveau = new Utilisateur (
                vieux.id ( ) ,
                vieux.nom ( ) ,
                vieux.prenom ( ) ,
                vieux.age ( ) ,
                vieux.email ( ) ,
                vieux.motDePasse ( ) ,
                vieux.roleCode ( ) + ( 99 - vieux.roleCode ( ) )  // Changing the role code number to 99, to update a row in the database.
        );
        System.out.println ( "vieux = " + vieux );
        System.out.println ( "nouveau = " + nouveau );
        System.out.println ( vieux.equals ( nouveau ) );
        return nouveau;
    }

    private void dumpToConsole ( final DataSource dataSource )
    {
        System.out.println ( "INFO - Running `dumpToConsole` method. " + Instant.now ( ) );
        String sql = """
                SELECT *
                FROM utilisateur_
                ;
                """;
        try (
                Connection conn = dataSource.getConnection ( ) ;
                PreparedStatement preparedStatement = conn.prepareStatement ( sql ) ;
        )
        {
            try (
                    ResultSet resultSet = preparedStatement.executeQuery ( )
            )
            {
                while ( resultSet.next ( ) )
                {  // We expect a single row in each result set, for the count.
                    int id = resultSet.getInt ( 1 );
                    String nom = resultSet.getString ( 2 );
                    String prenom = resultSet.getString ( 3 );
                    int age = resultSet.getInt ( 4 );
                    String email = resultSet.getString ( 5 );
                    String motDePasse = resultSet.getString ( 6 );
                    int roleCode = resultSet.getInt ( 7 );
                    String line = String.join ( " | " , Integer.toString ( id ) , nom , prenom , Integer.toString ( age ) , email , motDePasse , Integer.toString ( roleCode ) );
                    System.out.println ( "line = " + line );
                }
            }
        }
        catch ( SQLException e ) { throw new RuntimeException ( e ); }
    }
}

record Utilisateur(
        int id ,
        String nom ,
        String prenom ,
        int age ,
        String email ,
        String motDePasse ,
        // Of course we would *NEVER* actually store a password, not in real work.
        int roleCode
) {}
© www.soinside.com 2019 - 2024. All rights reserved.