package vovanhai.wordpress.bean;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import vovanhai.wordpress.util.MessageFactory;
import com.sun.mail.smtp.SMTPTransport;
@SuppressWarnings(“all”)
public class UserForm {
String url = “jdbc:mysql://localhost:3306/”;
String db = “application”;
String driver = “com.mysql.jdbc.Driver”;
String user = “root”;
String pass = “”;
Connection con = null;
Statement st;
ResultSet res;
public UserForm(){
loadDriver();
}
public void loadDriver(){
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
}
catch (Exception s){
System.out.println(“Error in loading driver: ”+s);
}
}
private Integer id;
private String firstName ;
private String lastName ;
private String userName ;
private String password ;
private String confirmPassword ;
private String email ;
private String address ;
private String select;
private String state ;
private String contactNumber ;
private List countryList= new ArrayList();
private List stateList= new ArrayList();
private boolean isUserNameDisabled;
private String buttonName=“Register”;
private String oldPwd;
private String newPwd;
private String newPwdConfirm;
private String text;
private Transport transport;
private Message message;
private Session session;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSelect() {
return select;
}
public void setSelect(String select) {
this.select = select;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public boolean getIsUserNameDisabled() {
return isUserNameDisabled;
}
public void setIsUserNameDisabled(boolean isUserNameDisabled) {
this.isUserNameDisabled = isUserNameDisabled;
}
public String getButtonName() {
return buttonName;
}
public void setButtonName(String buttonName) {
this.buttonName = buttonName;
}
public String getOldPwd(){
return oldPwd;
}
public void setOldPwd(String oldPwd){
this.oldPwd = oldPwd;
}
public String getNewPwd(){
return newPwd;
}
public void setNewPwd(String newPwd){
this.newPwd = newPwd;
}
public String getNewPwdConfirm(){
return newPwdConfirm;
}
public void setNewPwdConfirm(String newPwdConfirm){
this.newPwdConfirm = newPwdConfirm;
}
public String getText(){
return text;
}
public void setText(String text){
this.text = text;
}
public String changePassword() throws Exception {
if(validatePassword()){
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)context.getExternalContext().getSession(false);
int id = (Integer)session.getAttribute(“id”);
String query=“SELECT password FROM register where id=’”+ id + “‘”;
st = con.createStatement();
res = st.executeQuery(query);
boolean isPwdValid = false;
if(res.next()){
isPwdValid = res.getString(“password”).equals(getOldPwd());
}
if(isPwdValid){
query = “update register set password=’”+ getNewPwd()+“‘ where id=’”+ id +“‘”;
st.executeUpdate(query);
st.close();
res.close();
session.setAttribute(“id”, id);
return “success”;
}
else{
setText(“Please enter correct old password”);
return “failure”;
}
}
else{
return “failure”;
}
}
private boolean validatePassword(){
boolean status = true;
MessageFactory mf = new MessageFactory();
FacesContext ctx = FacesContext.getCurrentInstance();
if(newPwd.length() < 6 || newPwd.length() > 20){
ctx.addMessage(“changePwdForm:newPwd”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorPasswordLength”), null));
status = false;
}
Pattern p1 = Pattern.compile(“^[a-zA-Z0-9]+$”);
Matcher m1 = p1.matcher(newPwd);
boolean matchFound1 = m1.matches();
if(!matchFound1){
ctx.addMessage(“changePwdForm:newPwd”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorPassword”), null));
status = false;
}
if(!newPwdConfirm.equals(newPwd)){
ctx.addMessage(“changePwdForm:newPwdConfirm”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorPasswordConfirm”), null));
status = false;
}
return status;
}
public String editProfile() throws Exception{
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
int id = (Integer)session.getAttribute(“id”);
String query=“SELECT * FROM register where id=’”+ id + “‘”;
st = con.createStatement();
res = st.executeQuery(query);
if((res.next())){
setId(res.getInt(“id”));
setFirstName(res.getString(“firstName”));
setLastName(res.getString(“lastName”));
setUserName(res.getString(“userName”));
setPassword(res.getString(“password”));
setConfirmPassword(res.getString(“password”));
setEmail(res.getString(“email”));
setAddress(res.getString(“address”));
setSelect(res.getString(“country”));
setState(res.getString(“state”));
setContactNumber(res.getString(“contactNo”));
setIsUserNameDisabled(true);
setButtonName(“Save Changes”);
}
st.close();
res.close();
return “editSuccess”;
}
public String saveUser() throws Exception{
if (validateData()){
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
//if(getId().intValue() == 0){
if(getId() == null){
String query= “insert into register(firstName, lastName, userName, password, email, contactNo, address, country, state) values (‘”+ getFirstName() +“‘,’”+ getLastName() +“‘,’”+ getUserName() +“‘,’”+ getPassword() +“‘,’”+ getEmail() +“‘,’”+ getContactNumber() +“‘,’”+ getAddress() +“‘,’”+ getSelect() +“‘,’”+ getState() +“‘)”;
st = con.createStatement();
st.executeUpdate(query);
st.close();
sendMail(getEmail());
return “successUserRegistration”;
}
else{
String query = “update register set firstName=’”+ getFirstName()
+“‘, lastName=’”+ getLastName() +“‘, userName=’”+ getUserName()
+“‘, password=’”+ getPassword() +“‘, email=’”+ getEmail()
+“‘, contactNo=’”+ getContactNumber() +“‘, address=’”+ getAddress()
+“‘, country=’”+ getSelect() +“‘, state=’”+ getState()
+“‘ where id=”+ getId();
st = con.createStatement();
st.executeUpdate(query);
st.close();
session.setAttribute(“id”, id);
return “successUserUpdate”;
}
}
else{
return “error”;
}
}
public boolean validUser(){
String username = userName.trim();
boolean validUser=true;
try{
String query=“SELECT userName FROM register where userName=’”+ username + “‘”;
st = con.createStatement();
res = st.executeQuery(query);
if((res.next())){
validUser = false;
}
st.close();
res.close();
}
catch (SQLException s){
System.out.println(s);
}
return validUser;
}
public boolean validEmail(){
String email_check = email.trim();
boolean validEmail=true;
try{
String query=“SELECT email FROM register where email=’”+ email_check + “‘”;
st = con.createStatement();
res = st.executeQuery(query);
if((res.next())){
validEmail = false;
}
st.close();
res.close();
}
catch (SQLException s){
System.out.println(s);
}
return validEmail;
}
private boolean validateData() throws Exception {
boolean status = true;
MessageFactory mf = new MessageFactory();
FacesContext ctx = FacesContext.getCurrentInstance();
String firstname = firstName.trim();
if(!(((firstName.length())>=1) && ((firstName.length())<=25))){
ctx.addMessage(“UserForm:firstName”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorFirstNameLength”), null));
status = false;
}
Pattern p3 = Pattern.compile(“^[a-zA-Z]+$”);
Matcher m3 = p3.matcher(firstName);
boolean matchFound3 = m3.matches();
if (!matchFound3) {
ctx.addMessage(“UserForm:firstName”,new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorFirstName”), null));
status = false;
}
if(!(((lastName.length())>=1) && ((lastName.length())<=25))){
ctx.addMessage(“UserForm:lastName”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorLastNameLength”), null));
status = false;
}
Pattern p4 = Pattern.compile(“^[a-zA-Z]+$”);
Matcher m4 = p4.matcher(lastName);
boolean matchFound4 = m4.matches();
if (!matchFound4) {
ctx.addMessage(“UserForm:lastName”,new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorLastName”), null));
status = false;
}
//if(getId().intValue() == 0){
if(getId() == null){
//Checking User Name
String username = userName.trim();
if((username.length())==0){
ctx.addMessage(“UserForm:userName”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorUserNameBlank”), null));
status = false;
}
if((!(validUser()))){
ctx.addMessage(“UserForm:userName”,new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorValidUserName”), null));
status = false;
}
if((username.length())<6 || (username.length())>20 ){
ctx.addMessage(“UserForm:userName”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorUserNameLength”), null));
status = false;
}
String iChars = “!@#$%^&*()+=-[]\\\’;,/{}|\”:<>?”;
for (int i = 0; i < userName.length(); i++) {
if (iChars.indexOf(userName.charAt(i)) != -1) {
ctx.addMessage(“UserForm:userName”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorUserName”), null));
status = false;
break;
}
}
}
if((password.length())<6 || (password.length())>20){
ctx.addMessage(“UserForm:password”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorPasswordLength”), null));
status = false;
}
Pattern p1 = Pattern.compile(“^[a-zA-Z0-9]+$”);
Matcher m1 = p1.matcher(password);
boolean matchFound1 = m1.matches();
if (!matchFound1) {
ctx.addMessage(“UserForm:password”,new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorPassword”), null));
status = false;
}
if((confirmPassword.length())<6 || (confirmPassword.length())>20){
ctx.addMessage(“UserForm:confirmPassword”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorConfirmPasswordLength”), null));
status = false;
}
Pattern p2 = Pattern.compile(“^[a-zA-Z0-9]+$”);
Matcher m2 = p2.matcher(confirmPassword);
boolean matchFound2 = m2.matches();
if (!matchFound2) {
ctx.addMessage(“UserForm:confirmPassword”,new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorConfirmPasswordValid”), null));
status = false;
}
if (!confirmPassword.equals(password)) {
ctx.addMessage(“UserForm:confirmPassword”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorConfirmPassword”), null));
status = false;
}
//Checking Email address
Pattern p6 = Pattern.compile(“.+@.+\\.[a-z]+”);
Matcher m6 = p6.matcher(email);
boolean matchFound6 = m6.matches();
if (!matchFound6) {
ctx.addMessage(“UserForm:email”,new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorEmail”), null));
status = false;
}
if(getId()== null){
if((!(validEmail()))){
ctx.addMessage(“UserForm:email”,new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorValidEmail”), null));
status = false;
}
}
// End of checking Email address
String adrs = address.trim();
if((adrs.length())==0){
ctx.addMessage(“UserForm:address”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorAddressBlank”), null));
status = false;
}
String countryName = select.trim();
if((countryName.length())==0){
ctx.addMessage(“UserForm:country”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorCountryBlank”), null));
status = false;
}
String stateName= state.trim();
if((stateName.length())==0){
ctx.addMessage(“UserForm:state”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorStateBlank”), null));
status = false;
}
String cn = contactNumber.trim();
if((cn.length())==0){
ctx.addMessage(“UserForm:contactNumber”, new FacesMessage(FacesMessage.SEVERITY_ERROR, mf.getMessage(“errorContactNumberBlank”), null));
status = false;
}
if(getId() != null){
if(status==false){
setIsUserNameDisabled(true);
setButtonName(“Save Changes”);
}
}
return status;
}
public void sendMail(String email) throws Exception {
String smtpServer=“smtp.gmail.com”;
String from = “accp0708a@gmail.com”;//gmail account cá»§a bạn phải được cung cấp ở đây
String password=“aimabiet”;//máºt khẩu tháºt cá»§a gmail account cá»§a bạn dùng để chứng thá»± khi gá»i
String subject = “Successful Registeration”;
String content = “Thanks for registering with us. \n”;
content += “Your login details are: \n”;
content += “Username : ”;
content += getUserName();
content += “\n”;
content += “Password: ”;
content += getPassword();
content+=“\ngo to http://vovanhai.wordpress.com to see more…!”;
send(smtpServer, email, from, password, subject, content);
}
public void send(String smtpServer, String to, String from,String psw,
String subject, String body) throws Exception{
Properties props = System.getProperties();
// –
props.put(“mail.smtp.host”, smtpServer);
props.put(“mail.smtp.port”, “587″);
props.put(“mail.smtp.starttls.enable”,“true”);
final String login = from;
final String pwd = psw;
Authenticator pa = null; //default: no authentication
if (login != null && pwd != null) { //authentication required?
props.put(“mail.smtp.auth”, “true”);
pa = new Authenticator (){
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(login, pwd);
}
};
}//else: no authentication
Session session = Session.getInstance(props, pa);
// – Create a new message –
Message msg = new MimeMessage(session);
// – Set the FROM and TO fields –
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
to, false));
// – Set the subject and body text –
msg.setSubject(subject);
msg.setText(body);
// – Set some other header information –
msg.setHeader(“X-Mailer”, “LOTONtechEmail”);
msg.setSentDate(new Date());
msg.saveChanges();
// – Send the message –
Transport.send(msg);
System.out.println(“Message sent OK.”);
}
} |
Xuân Anh said
Em chào thầy ạ ! Lại làm phiền thầy rồi !
Thầy cho em hỏi khi tạo xong các file Beans trên thì mình truy suất và hiển thị thành công cho người dùng bên trang JSP bằng cách nào được ạ !
Nguyễn Thị Thanh Phúc said
Em thưa thầy.! Em cũng có câu hỏi giống bạn Xuân Anh!. Em mong thầy sớm hồi âm cho bọn e với ạ.Em cám ơn thầy nhiều nhiều ạ.
Võ Văn Hải said
Đọc kỹ cả ứng dụng bạn sẽ thấy. (theo cú pháp #{})