示例我有一个 JSF 托管 bean,并且我有创建用户的方法:
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";
}
我读到 JSF managedBean 应该只用于导航,这里我的问题是在 JSF beanie 中进行这种验证是否正确?例如,我们是否应该创建一个服务层来完成验证?例如,像这样:
@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;
}
}
然后在jsf bean中只有这个:
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;
}
}
那是好事吗?在 Java EE 中划分代码的最佳方法是什么?