使用Struts制作的WebApplication不断向数据库中插入空值

时间:2018-11-29 23:35:40

标签: java mysql jdbc struts2

我正在研究一个基于用户的示例Java Web应用程序。当我尝试通过注册将用户添加到我的数据库时。在前端捕获数据后,记录将存储为空值

即我的用户表的一行将包含值(7,null,null,null,null)(使用模板ID(主键),f_name,l_name,email和password)。

以下是我认为可能会导致问题的文件

User.java

package com.ysg.data;

import com.ysg.service.PasswordEncrypter;
import java.io.Serializable;
import java.util.Date;
import java.util.Objects;

public class User implements Serializable {
    private String id;
    private String password;
    private String firstName;
    private String lastName;
    private String email;

    public User(){
        // default
    }

    public User( String password, boolean isEncrypted, String firstName, String 
    lastName, String email){
        this.password = isEncrypted ? password : encrypt(password);
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }  //getters and setters follow

UserRepository.java

package com.ysg.repository;

import com.ysg.data.User;
import com.ysg.exception.DuplicateItemException;
import com.ysg.exception.RepositoryException;
import com.ysg.util.MySQLHelper;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class UserRepository implements RepositoryInt<User> {
    private static final String INSERT = "INSERT INTO ysg.users (f_name, l_name, email, password) values (?, ?, ?, ?)";
    private static final String USER_LOGIN = "SELECT * FROM ysg.users WHERE email=? and password=?";
    private static final String USER_FETCH = "SELECT * FROM ysg.users WHERE email='";
    private static final String FIRSTNAME = "f_name";
    private static final String LASTNAME = "l_name";
    private static final String EMAIL= "email";
    private static final String PASSWORD = "password";

    public UserRepository(){
        // default
    }

    @Override
    public User login(User obj){
        User result = find(obj);
        if (result != null) {
            return result;
        }
        return null;
    }
    @Override


    public User register(User obj){
        if (obj != null && (find(obj) == null)) {
            return add(obj);
        }
        return null;
    }



    private User add(User user){
        Connection conn = null;
        try {
            conn = getConnection();
            PreparedStatement stmt = conn.prepareStatement(INSERT);
            stmt.setString(1, user.getFirstName());
            stmt.setString(2, user.getLastName());
            stmt.setString(3, user.getEmail());
            stmt.setString(4, user.getPassword());
            stmt.execute();
            closeStatement(stmt);
            return user;
        }
        catch (SQLException ex) {
            if (ex.getMessage().contains("Duplicate")) {
                System.out.println("Item with duplicate id already exists in repository");
                throw new DuplicateItemException("Item with duplicate id already exists in repository");
            }
            else {
                ex.printStackTrace();
                System.out.println("Failed to add item to repository");
                throw new RepositoryException(ex);
            }
        }
        finally {
            closeConnection(conn);
        }
    }

    private User fetch(User user){
        Connection conn = null;
        try {
            conn = getConnection();
            Statement stmt = conn.createStatement();
            stmt.execute(USER_FETCH + user.getEmail()+ "'");
            ResultSet resultSet = stmt.getResultSet();
            User result = marshall(resultSet);
            closeStatement(stmt);
            return result;
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            System.out.println("Failed to fetch item from repository");
            throw new RepositoryException(ex);
        }
        finally {
            closeConnection(conn);
        }
    }

    private User find(User user){
        Connection conn = null;
        try {
            conn = getConnection();
            PreparedStatement stmt = conn.prepareStatement(USER_LOGIN);
            stmt.setString(1, user.getEmail());
            stmt.setString(2, user.getPassword());
            ResultSet resultSet = stmt.executeQuery();
            User result = marshall(resultSet);
            closeStatement(stmt);
            return result;
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            System.out.println("Failed to add item to repository");
            throw new RepositoryException(ex);
        }
        finally {
            closeConnection(conn);
        }
    }

    private User marshall(ResultSet result) throws RepositoryException, SQLException{
        if (result == null) {
            return null;
        }
        User user = null;
        if (result.next()) {
           // String id = result.getString(ID);
            String password = result.getString(PASSWORD);
            String firstName = result.getString(FIRSTNAME);
            String lastName = result.getString(LASTNAME);
            String email = result.getString(EMAIL);
            user = new User(password, true, firstName, lastName, email);
        }
        return user;
    }

    private Connection getConnection(){
        return MySQLHelper.getConnection();
    }

    private static void closeStatement(Statement stmt){
        if (stmt != null) {
            try {
                stmt.close();
                //stmt = null;
            }
            catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private void closeConnection(Connection conn){
        if (conn != null) {
            try {
                conn.close();
                conn = null;
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

MySQLHelper.java

package com.ysg.util;

import com.ysg.data.User;
import com.ysg.exception.DuplicateItemException;
import com.ysg.exception.RepositoryException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class MySQLHelper {
    private static final String INSERT_USER = "INSERT INTO  users(f_name, l_name, email, password) values (?, ?, ?, ?)";
    private static final String USER_FETCH = "SELECT * FROM users WHERE id='";
    private static final String FETCH_ALL = "SELECT * FROM users";
    private static final String COUNT_ALL_USERS = "SELECT COUNT(*) FROM users";
    private static final String DELETE_ALL = "DELETE FROM users";
    private static final String ID = "id";
    private static final String EMAIL = "email";
    private static final String PASSWORD = "password";
    private static final String FIRSTNAME = "f_name";
    private static final String LASTNAME = "l_name";
    private static final String DS_NAME = "jdbc/sen301DS";
    private static Context envCtx;
    private static DataSource ds;

    static {
        try {
            Context ctx = new InitialContext();
            envCtx = (Context) ctx.lookup("java:/comp/env");
            System.out.println(envCtx);
        }
        catch (Exception ex) {
            System.out.println("ConnectionPool will not be available - only direct connection can be used");
        }
    }

    public static List<User> fetch() throws SQLException{
        Connection conn = null;
        try {
            conn = getConnection();
            Statement stmt = conn.createStatement();
            stmt.execute(FETCH_ALL);
            ResultSet resultSet = stmt.getResultSet();
            List<User> result = marshall(resultSet);
            closeStatement(stmt);
            return result;
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            throw ex;
        }
        finally {
            closeConnection(conn);
        }
    }

    public static User fetch(String id) throws SQLException{
        Connection conn = null;
        try {
            conn = getConnection();
            Statement stmt = conn.createStatement();
            stmt.execute(USER_FETCH + id + "'");
            ResultSet resultSet = stmt.getResultSet();
            List<User> result = marshall(resultSet);
            closeStatement(stmt);
            return result.get(0);
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            throw ex;
        }
        finally {
            closeConnection(conn);
        }
    }

    public static User add(User user){
        Connection conn = null;
        try {
            conn = getConnection();
            PreparedStatement stmt = conn.prepareStatement(INSERT_USER);
            stmt.setString(1, user.getFirstName());
            stmt.setString(2, user.getLastName());
            stmt.setString(3, user.getEmail());
            stmt.setString(4, user.getPassword());
            stmt.execute();
            closeStatement(stmt);
            return user;
        }
        catch (SQLException ex) {
            if (ex.getMessage().contains("Duplicate")) {
                System.out.println("Item with duplicate id already exists in repository");
                throw new DuplicateItemException("Item with duplicate id already exists in repository");
            }
            else {
                ex.printStackTrace();
                System.out.println("Failed to add item to repository");
                throw new RepositoryException(ex);
            }
        }
        finally {
            closeConnection(conn);
        }
    }

    public static int countusers() throws SQLException{
        Connection conn = null;
        try {
            conn = getConnection();
            Statement stmt = conn.createStatement();
            stmt.execute(COUNT_ALL_USERS);
            ResultSet resultSet = stmt.getResultSet();
            int count = 0;
            if (resultSet.next()) {
                count = resultSet.getInt(1);
            }
            closeStatement(stmt);
            return count;
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            throw ex;
        }
        finally {
            closeConnection(conn);
        }
    }

    public static void reset() throws SQLException{
        Connection conn = null;
        try {
            conn = getConnection();
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(DELETE_ALL);
            closeStatement(stmt);
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            throw ex;
        }
        finally {
            closeConnection(conn);
        }
    }

    private static List<User> marshall(ResultSet result) throws SQLException{
        List<User> list = new ArrayList<User>();
        if (result == null) {
            return list;
        }
        while (result.next()) {
            String firstName = result.getString(FIRSTNAME);
            String lastName = result.getString(LASTNAME);
            String email = result.getString(EMAIL);
            String passwd = result.getString(PASSWORD);
            User user = new User(passwd, true, firstName, lastName, email);
            list.add(user);
        }
        return list;
    }

    private static DataSource getDataSource(){
        DataSource ds = null;
        try {
            ds = (DataSource) envCtx.lookup(DS_NAME);
        }
        catch (NamingException ex) {
            ex.printStackTrace();
            throw new RepositoryException("Failed to get DataSource");
        }
        return ds;
    }

    public static Connection getConnection(){
        Connection con = null;
        try {
            con = getDataSource().getConnection();
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            throw new RepositoryException("Failed to get connection to database server");
        }
        catch (Exception ex) {
            con = getDirectConnection();
        }
        return con;
    }

    private static Connection getDirectConnection(){
        try {
            String conURL = "jdbc:mysql://localhost:3306/ysg?serverTimezone=UTC&useSSL=false&" + "user=sen301&password=sen301";
            return DriverManager.getConnection(conURL);
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            throw new RepositoryException("Failed to get direct connection to database server");
        }
        catch (Exception ex) {
            ex.printStackTrace();
            throw new RepositoryException(ex);
        }
    }

    private static void closeStatement(Statement stmt){
        if (stmt != null) {
            try {
                stmt.close();
                stmt = null;
            }
            catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    private static void closeConnection(Connection conn){
        if (conn != null) {
            try {
                conn.close();
                conn = null;
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

0 个答案:

没有答案