Creating managed beans

Login and Registration application uses three java file to manage and process the logic of the application.

Creating managed beans

Creating Managed Beans

    

Login and Registration application uses three java file to manage and process the logic of the application.

  1. LoginForm.java
  2. UserForm.java
  3. RetrievePassword.java
  1. LoginForm.java

This java file handles the login and logout process for the user. Its validUser() method checks the authenticity of the user. If user is valid then signals the user to access rest of the application.

import java.util.*;
import java.sql.*;
import java.util.regex.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.faces.context.*;
import javax.faces.application.*;
import javax.faces.application.FacesMessage;

public class LoginForm  {
  private String text;
  private String userName;
  private String password;

  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 getText() {
  return text;
  }
  public void setText(String text){
  this.text = text;
  }

  String url = "jdbc:mysql://localhost:3306/";
  String db = "application";
  String driver = "com.mysql.jdbc.Driver";
  String user = "root";
  String pass = "root";
  Connection con = null;
  ResultSet res;

  public String validUser() throws Exception{
  String returnString = "success";
  try{
  Class.forName(driver);
  try{
  con = DriverManager.getConnection(url+db, user, pass);
  Statement st = con.createStatement();
  String query="SELECT * FROM  register where 
   userName='"+  userName + "' && password='" + password+"'";
  res = st.executeQuery(query);
  if(res.next()){  
  int id = res.getInt("id");
  String username = res.getString("userName");
  
  FacesContext context = FacesContext.getCurrentInstance();
  HttpSession session = 
   (HttpSession)context.getExternalContext().getSession(true);
  session.setAttribute("id", id);
  session.setAttribute("username", username);
  }
  else{
  setText("User Name or Password is incorrect.");
  returnString = "failure";
  }
  }
  catch (SQLException s){
  System.out.println(s);
  }
  }
  catch (ClassNotFoundException s){
  System.out.println(s);
  }
  return returnString;
  }

  public String logout(){
  FacesContext context = FacesContext.getCurrentInstance();
  HttpSession session = 
   (HttpSession) context.getExternalContext().getSession(true);
  if(session==null){
  return "invalid";
  }
  else{
  session.invalidate();
  return "logoutsuccess";
  }
  }  
}  
UserForm.java

This java file is created to change password by changePassword() method, showing profile information when user clicks to update user profile by editProfile() method, saving the new or changed information of the user by saveUser() method, checking the validity of the user by validUser() method, sending email to the mail id of the registered user by sendMail() method.

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.smtp.SMTPTransport;
import java.io.*;
import java.sql.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


import java.util.*;
import java.util.regex.*;


import util.MessageFactory;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.faces.context.*;
import javax.faces.application.FacesMessage;
import javax.faces.model.SelectItem;
import javax.faces.event.ValueChangeEvent;
import javax.faces.context.FacesContext;


public class UserForm  {
  
  String url = "jdbc:mysql://localhost:3306/";
  String db = "application";
  String driver = "com.mysql.jdbc.Driver";
  String user = "root";
  String pass = "root";
  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){
  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){
  //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().intValue() == 0){
  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().intValue() != 0){
  if(status==false){
  setIsUserNameDisabled(true);
  setButtonName("Save Changes");
  }
  }

  return status;
  }
public void setMessage(String fromAddress,String toAddress,String subject,String content) 
throws Exception {
  String[] addresses = {toAddress};
  setMessage(fromAddress,addresses,subject,content);
  }
  public void sendMail(String email) throws Exception {
  String from = "[email protected] ";
  String to[] = new String[]{email};
  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();

  setMessage(from,to,subject,content);
  setSMTPServer("192.168.10.204",25,null,null);

  send();
  }

public void setMessage(String fromAddress,String[] toAddresses,String subject,String content) 
throws Exception {
  session = Session.getInstance(System.getProperties());
  message = new MimeMessage(session);
  
  message.setFrom(new InternetAddress(fromAddress));
  InternetAddress[] toIntAdds = new InternetAddress[toAddresses.length];

  for (int i=0;i<toAddresses.length;i++)
  toIntAdds[i] = new InternetAddress(toAddresses[i]);

  message.setRecipients(Message.RecipientType.TO,toIntAdds);
  message.setSubject(subject);
  message.setSentDate(new java.util.Date());
  message.setText(content);
  }

  public void setSMTPServer(String host,int port,String user,String password) throws Exception{
  transport = new SMTPTransport(session,new URLName(host));
  transport.connect(host,port,null,null);
  }

  public void send() throws Exception{
  message.saveChanges();
  transport.sendMessage(message, message.getAllRecipients());
  System.out.println("Message is sent.");
  transport.close();
  }
}

Above files use "MessageFactory.java" file to get the value of the key from the resource bundle file"LRAppResourceBundle.properties".

MessageFactory.java 

package util;

import java.util.ResourceBundle;
import java.util.Locale;
import javax.faces.context.FacesContext;

public class MessageFactory {
  ResourceBundle bundle;
  Locale locale;
  
  public MessageFactory() {
  locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
  bundle = ResourceBundle.getBundle("LRAppResourceBundle", locale);
  }
  public String getMessage(String key) {
  return bundle.getString(key);
  }
}