Example I have a JSF managed bean, and in I have method to create user:
public String createNewAccount() {
FacesContext context = FacesContext.getCurrentInstance();
Map requestParameterMap = (Map) context.getExternalContext().getRequestParameterMap();
try {
String userRole = requestParameterMap.get("userRole").toString();
String active = requestParameterMap.get("active").toString();
Boolean act = Boolean.parseBoolean(active);
user.setRole(userRole);
user.setActive(act);
if ((user.getEmail() != null) && (userDao.findEmailExist(user.getEmail()))) {
sendErrorMessageToUser("A user with the given email address exists in the databasee");
return null;
} else {
userDao.create(user);
}
} catch (EJBException e) {
sendErrorMessageToUser("Register error");
return null;
}
return "newAccountCreated";
}
I read that JSF managedBean should be only used to navigation, and here my question is whether such doing validation in JSF beanie is correct? Should we create a service layer for example, in which the verification will be accomplished? For example, like this:
@Stateless
public class UserDao implements UserDaoLocal {
@PersistenceContext
private EntityManager em;
private User user;
@Override
public void create(User user) {
em.persist(user);
}
@Stateless
public class UserDaoService implements UserDaoServiceLocal {
@EJB
private UserDaoLocal userDao
private User user;
@Override
public String create(User user) {
if(findEmailExist(user.email) {
return "emailExist";
} else {
userDao.create(user);
return "create";
}
}
@Override
public boolean findEmailExist(String email) {
try {
Query q = em.createNamedQuery("User.findByEmail");
q.setParameter("email", email);
user = (User) q.getSingleResult();
return true;
} catch (Exception e) {
System.out.println("Błąd email: " + e.getMessage());
return false;
}
}
and then in jsf bean only have this:
public String createNewAccount() {
FacesContext context = FacesContext.getCurrentInstance();
Map requestParameterMap = (Map) context.getExternalContext().getRequestParameterMap();
try {
String userRole = requestParameterMap.get("userRole").toString();
String active = requestParameterMap.get("active").toString();
Boolean act = Boolean.parseBoolean(active);
user.setRole(userRole);
user.setActive(act);
String result userDaoService.create(user);
if (result = "emailExist") {
sendErrorMessageToUser("A user with the given email address exists in the database");
return null;
} else
return result;
}
} catch (EJBException e) {
sendErrorMessageToUser("Error registration");
return null;
}
}
That is a good? What is the best way out to partition code in Java EE?