Architecting Applications for the Web Lab 03 Interceptors and Tags Mục tiêu - Sử dụng Interceptor thừa kế Struts-default xây dựng custom interceptor Sử dụng struts-tags để xây dựng trang jsp Phần I Bài tập step by step Bài tập: xây dựng chức register,search,update,delete user Dùng Interceptor để filter user login giữ lưới liệu update, delete user Phần 1: Xây dựng chức register,search,update,delete User Step 1: Sử dụng Tags để xây dựng giao diện register.jsp: REGISTER FORM - searchuser.jsp: IT Research Department @BKAP 2015 Trang / 14 Architecting Applications for the Web Search User No UserName Password FirstName LastName Gender BirthDate Phone Email IsDelete Delete Update IT Research Department @BKAP 2015 Trang / 14 Architecting Applications for the Web Delete - success.jsp: Registration Successful. Welcome User: Please wait for admin approval! Back to login - userinformation.jsp: User Information UserName: FirstName: LastName: BirthDate: Gender: Address: BirthPlace: Phone: Email: IT Research Department @BKAP 2015 Trang / 14 Architecting Applications for the Web Step 2: Xây dựng Action cho chức register,update,delete,search user - Session2Action.java import ConnectDB.connectDB; import Entity.UserEntity; import static com.opensymphony.xwork2.Action.ERROR; import static com.opensymphony.xwork2.Action.SUCCESS; import com.opensymphony.xwork2.ActionSupport; import java.io.File; import java.util.ArrayList; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.struts2.interceptor.ServletRequestAware; /** * * @author DELL */ public class Session2Action extends ActionSupport implements ServletRequestAware{ private String userName; private String password; private String confirmpassword; private String firstName; private String lastName; private Date birthDate; private String gender; private String address; private String birthPlace; private String phone; private String email; private String isDelete; private File image; private String imageContentType; private String imageFileName; private HttpServletRequest servletRequest; ArrayList listuser = new ArrayList(); private String sr_userName; private String sr_firstName; private String sr_lastName; private String sr_email; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; IT Research Department @BKAP 2015 Trang / 14 Architecting Applications for the Web } public void setPassword(String password) { this.password = password; } public String getConfirmpassword() { return confirmpassword; } public void setConfirmpassword(String confirmpassword) { this.confirmpassword = confirmpassword; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getBirthPlace() { return birthPlace; } IT Research Department @BKAP 2015 Trang / 14 Architecting Applications for the Web public void setBirthPlace(String birthPlace) { this.birthPlace = birthPlace; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getIsDelete() { return isDelete; } public void setIsDelete(String isDelete) { this.isDelete = isDelete; } public File getImage() { return image; } public void setImage(File image) { this.image = image; } public String getImageContentType() { return imageContentType; } public void setImageContentType(String imageContentType) { this.imageContentType = imageContentType; } public String getImageFileName() { return imageFileName; } public void setImageFileName(String imageFileName) { this.imageFileName = imageFileName; } public HttpServletRequest getServletRequest() { return servletRequest; } IT Research Department @BKAP 2015 Trang / 14 Architecting Applications for the Web @Override public void setServletRequest(HttpServletRequest servletRequest) { this.servletRequest = servletRequest; } public ArrayList getListuser() { return listuser; } public void setListuser(ArrayList listuser) { this.listuser = listuser; } public String getSr_userName() { return sr_userName; } public void setSr_userName(String sr_userName) { this.sr_userName = sr_userName; } public String getSr_firstName() { return sr_firstName; } public void setSr_firstName(String sr_firstName) { this.sr_firstName = sr_firstName; } public String getSr_lastName() { return sr_lastName; } public void setSr_lastName(String sr_lastName) { this.sr_lastName = sr_lastName; } public String getSr_email() { return sr_email; } public void setSr_email(String sr_email) { this.sr_email = sr_email; } @Override public String execute() throws Exception{ return SUCCESS; } public String register() throws Exception { String path = "Upload/"; String filePath = this.servletRequest.getSession().getServletContext().getRealPath(path); File uploadDir = new File(filePath); FileUtils.copyFile(this.image, new File(uploadDir, this.userName)); String destFilep = uploadDir + this.userName; ConnectDB.connectDB conn = new connectDB(); IT Research Department @BKAP 2015 Trang / 14 Architecting Applications for the Web Boolean rel = conn.registerUser(getUserName(), getPassword(), getFirstName(), getLastName(), getBirthDate(), getGender(), getAddress(), getBirthPlace(), getPhone(), getEmail(), destFilep); if (rel) { return SUCCESS; } else { return ERROR; } } public String searchUser() throws Exception { ConnectDB.connectDB conn = new connectDB(); this.listuser = conn.searchAccount(sr_userName, sr_firstName, sr_lastName, sr_email); return SUCCESS; } public String deleteUser() throws Exception { ConnectDB.connectDB conn = new connectDB(); boolean result = conn.deleteAccount(userName); } if (result) { return SUCCESS; } return ERROR; public String updateUser() throws Exception { ConnectDB.connectDB conn = new connectDB(); Boolean rel = conn.UpdateAccount(userName, password, firstName, lastName, birthDate, gender, phone, email, isDelete); if (rel) { return SUCCESS; } return ERROR; } } - ConnectDB.java public boolean registerUser(String userName, String password, String firstName, String lastName, Date birthDate, String gender,String address,String birthPlace, String phone, String email, String image) throws Exception { Connection conn = null; PreparedStatement prest = null; String sql = "INSERT INTO [dbo].[ST_USER] ([USERNAME],[PASSWORD],[FIRSTNAME],[LASTNAME], [BIRTHDATE],[GENDER],[ADDRESS],[BIRTHPLACE],[PHONE],[EMAIL],[IMAGE],[ISDELETE],[GROUP_ID]) "; sql += "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"; try { conn = DBconnection(); prest = conn.prepareStatement(sql); prest.setString(1, userName); prest.setString(2, password); prest.setString(3, firstName); prest.setString(4, lastName); java.text.SimpleDateFormat sdatefmt = new SimpleDateFormat("yyyy-MM-dd"); String birthsim = sdatefmt.format(birthDate); birthsim = birthsim.trim(); Date birthfmt = sdatefmt.parse(birthsim); IT Research Department @BKAP 2015 Trang / 14 Architecting Applications for the Web java.sql.Date sqlbirth = new java.sql.Date(birthfmt.getTime()); } prest.setDate(5, sqlbirth); prest.setString(6, gender); prest.setString(7, address); prest.setString(8, birthPlace); prest.setString(9, phone); prest.setString(10, email); prest.setString(11, image); prest.setString(12, "PENDING"); prest.setInt(12, 2); int row = prest.executeUpdate(); if (row > 0) { return true; } } catch (SQLException ex) { HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("SQLErrors", ex.getMessage()); } finally { if (conn != null) { conn.close(); } if (prest != null) { prest.close(); } } return false; public ArrayList searchAccount(String userName, String firstName, String lastName, String email) throws SQLException { Connection conn = null; PreparedStatement prest = null; ArrayList listuser = new ArrayList(); String sql = "SELECT * FROM [dbo].[ST_USER]"; sql += " WHERE USERNAME LIKE ? AND FIRSTNAME LIKE ? AND LASTNAME LIKE ? AND EMAIL LIKE ?"; try { conn = DBconnection(); prest = conn.prepareStatement(sql); prest.setString(1, "%" + userName + "%"); prest.setString(2, "%" + firstName + "%"); prest.setString(3, "%" + lastName + "%"); prest.setString(4, "%" + email + "%"); ResultSet rs = prest.executeQuery(); while (rs.next()) { Entity.UserEntity user = new UserEntity(); user.setUserName(rs.getString("username")); user.setPassword(rs.getString("password")); user.setFirstName(rs.getString("firstname")); user.setLastName(rs.getString("lastname")); Date bdate = new java.sql.Date(rs.getDate("birthdate").getTime()); user.setBirthDate(bdate); user.setGender(rs.getString("gender")); user.setAddress(rs.getString("address")); user.setBirthPlace(rs.getString("birthPlace")); user.setPhone(rs.getString("phone")); user.setEmail(rs.getString("email")); IT Research Department @BKAP 2015 Trang / 14 Architecting Applications for the Web user.setImage(rs.getString("image")); user.setIsDelete(rs.getString("isdelete")); user.setGroup_id(rs.getInt("group_id")); listuser.add(user); } } catch (SQLException ex) { HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("SQLErrors", ex.getMessage()); } finally { if (conn != null) { conn.close(); } if (prest != null) { prest.close(); } } return listuser; } public boolean deleteAccount(String userName) throws Exception { Connection conn = null; PreparedStatement prest = null; String sql = "UPDATE [dbo].[ST_USER] SET ISDELETE = 'DISABLE' WHERE USERNAME = ?"; try { conn = DBconnection(); prest = conn.prepareStatement(sql); prest.setString(1, userName); int row = prest.executeUpdate(); if (row > 0) { return true; } } catch (SQLException ex) { HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("SQLErrors", ex.getMessage()); } finally { if (conn != null) { conn.close(); } if (prest != null) { prest.close(); } } return false; } public boolean UpdateAccount(String userName, String password, String firstName, String lastName, Date birthDate, String gender, String phone, String email,String isDelete) throws Exception { Connection conn = null; PreparedStatement prest = null; String sql = "UPDATE [dbo].[ST_USER] "; sql += "SET FIRSTNAME=?,LASTNAME=?,BIRTHDATE=?,GENDER=?,EMAIL=?,PHONE=?,ISDELETE=? "; sql += "WHERE USERNAME = ?"; try { conn = DBconnection(); prest = conn.prepareStatement(sql); prest.setString(1, firstName); prest.setString(2, lastName); java.text.SimpleDateFormat sdatefmt = new SimpleDateFormat("yyyy-MM-dd"); IT Research Department @BKAP 2015 Trang 10 / 14 Architecting Applications for the Web String birthsim = sdatefmt.format(birthDate); birthsim = birthsim.trim(); Date birthfmt = sdatefmt.parse(birthsim); java.sql.Date sqlbirth = new java.sql.Date(birthfmt.getTime()); prest.setDate(3, sqlbirth); prest.setString(4, gender); prest.setString(5, email); prest.setString(6, phone); prest.setString(7, isDelete); prest.setString(8, userName); int row = prest.executeUpdate(); if (row > 0) { return true; } } catch (SQLException e) { HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("SQLErrors", e.getMessage()); } finally { if (conn != null) { conn.close(); } if (prest != null) { prest.close(); } } return false; } Step 3:Cấu hình Struts.xml register.jsp success.jsp error.jsp searchuser.jsp SearchUser SearchUser Step 4: Build and Run: - Register: IT Research Department @BKAP 2015 Trang 11 / 14 Architecting Applications for the Web IT Research Department @BKAP 2015 Trang 12 / 14 Architecting Applications for the Web - Search, Delete, Update User: Phần 2: Dùng interceptor Srep 1: Trong phần ta sử dụng Interceptor chaining để keep data ta update delete user Step 2: Tạo custom interceptor để tính thời gian login login: Source Packages new other Struts2 Interceptor Name: LoginInterceptor, package: Interceptor - LoginInterceptor.java: package Interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; /** * * @author DELL */ public class LoginInterceptor implements Interceptor { public LoginInterceptor() { } @Override public void destroy() { System.out.println("Destroying MyLoggingInterceptor "); } @Override public void init() { System.out.println("Initializing MyLoggingInterceptor "); } @Override public String intercept(ActionInvocation actionInvocation) throws Exception { String className = actionInvocation.getClass().getName(); long startTime = System.currentTimeMillis(); IT Research Department @BKAP 2015 Trang 13 / 14 Architecting Applications for the Web System.out.println("Before calling action: " + className); String result = actionInvocation.invoke(); long endTime = System.currentTimeMillis(); System.out.println("After calling action: " + className + " Time taken: " + (endTime - startTime) + " ms"); return result; } } Step 3: Cấu hình file Struts.xml useriformation.jsp loginfailure.jsp IT Research Department @BKAP 2015 Trang 14 / 14 ... UserName: ... name="sr_userName" label="User Name" size="50"/> No