比如我有一個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豆唯一有此:
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中分區代碼的最佳方式是什麼?
這是基本的MVC架構。查看圖層(在您的情況下,JSF託管bean)只需完成將表單轉換爲可管理數據的工作。處理這些數據和DAO訪問與該層無關。 –