struts2學習筆記(三)—— 在使用者註冊程式中使用驗證框架
阿新 • • 發佈:2019-01-25
package register.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import register.entity.User; import register.exceptions.UsernameExistException; public class UserDao { public UserDao(){ String driverClass="com.mysql.jdbc.Driver"; try{ Class.forName(driverClass); }catch(ClassNotFoundException ce){ ce.printStackTrace(); } } public Connection getConnection() throws SQLException{ String url="jdbc:mysql://localhost:3307/user"; String user="tankcat_2"; String pw="wxt222$$$"; return DriverManager.getConnection(url,user,pw); } public User register(User user) throws SQLException, UsernameExistException{ Connection conn=null; PreparedStatement pstmt=null; ResultSet rs=null; try{ conn=getConnection(); String sql="select * from reg_user where username = ?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, user.getUsername()); rs=pstmt.executeQuery(); if(rs.next()){ throw new UsernameExistException(); } sql="insert into reg_user(username,password,sex,email,pwd_question,pwd_answer,reg_date) values(?,?,?,?,?,?,?)"; pstmt=conn.prepareStatement(sql); pstmt.setString(1, user.getUsername()); pstmt.setString(2, user.getPassword()); pstmt.setBoolean(3, user.getSex()); pstmt.setString(4, user.getEmail()); pstmt.setString(5, user.getPwdQuestion()); pstmt.setString(6,user.getPwdAnswer()); pstmt.setTimestamp(7, new java.sql.Timestamp(user.getRegDate().getTime())); pstmt.execute(); rs=pstmt.executeQuery("select last_insert_id()"); if(rs.next()){ user.setId(rs.getInt(1)); }else{ return null; } }catch(SQLException se){ throw se; }finally{ closeResultSet(rs); closePreparedStatement(pstmt); closeConnection(conn); } return user; } private void closeResultSet(ResultSet rs) { // TODO Auto-generated method stub if(rs!=null){ try{ rs.close(); }catch(SQLException se){ se.printStackTrace(); } rs=null; } } private void closePreparedStatement(PreparedStatement pstmt) { // TODO Auto-generated method stub if(pstmt!=null){ try{ pstmt.close(); }catch(SQLException se){ se.printStackTrace(); } pstmt=null; } } private void closeConnection(Connection conn) { // TODO Auto-generated method stub if(conn!=null){ try{ conn.close(); }catch(SQLException se){ se.printStackTrace(); } conn=null; } } }
struts.xml檔案的配置