81,092
社区成员
发帖
与我相关
我的任务
分享
@RequestMapping("/regist")
public ModelAndView regist(HttpServletRequest request, User user) throws Exception {
if (checkParams(new String[] { user.getUsername(), user.getPassword() })) {
//TODO @Transaction check if the account has already exist
try {
userService.saveUser(user);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("regist"+e.getMessage());
request.setAttribute("describe", e.getMessage());
}
request.setAttribute("username", user.getUsername());
request.setAttribute("password", user.getPassword());
System.out.println(user);
return new ModelAndView("succ");
}
return new ModelAndView("regist");
}
@Transactional(rollbackFor = Exception.class)
public void saveUser(User user) throws Exception {
if (user != null && user.getId() != null) {
userDao.updateUser(user);
} else {
// TODO find if there is a repetition, can also use SQL
try {
List<User> allUser = userDao.getUser();
userDao.insertUser(user);
for (User _user : allUser) {
if (_user.getUsername().equals(user.getUsername()))
throw new Exception("The account is exist!");
}
} catch (Exception e) {
throw e;
}
}
}
代码没问题,只是try是多余的
@Transactional(rollbackFor = Exception.class)
public void saveUser(User user) throws Exception {
if (user != null && user.getId() != null) {
userDao.updateUser(user);
} else {
// TODO find if there is a repetition, can also use SQL
List<User> allUser = userDao.getUser();
userDao.insertUser(user);
for (User _user : allUser) {
if (_user.getUsername().equals(user.getUsername()))
throw new Exception("The account is exist!");
}
}
}
或者在catch加上TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
@Transactional(rollbackFor = Exception.class)
public void saveUser(User user) throws Exception {
if (user != null && user.getId() != null) {
userDao.updateUser(user);
} else {
// TODO find if there is a repetition, can also use SQL
try {
List<User> allUser = userDao.getUser();
userDao.insertUser(user);
for (User _user : allUser) {
if (_user.getUsername().equals(user.getUsername()))
throw new Exception("The account is exist!");
}
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw e;
}
}
}