服务层和控制器在实践中的区别
我读过很多关于服务层和控制器之间差异的理论,我对如何在实践中实现这一点有一些疑问。服务层和控制器的一个答案是:谁负责什么?说:
我试图限制控制器做与验证http参数相关的工作,决定用什么参数调用什么服务方法,在httpsession或请求中放置什么,重定向或转发到什么视图,或类似的Web相关的东西。
危险信号:如果出现以下情况,我的控制器体系结构可能会变坏:
控制器向服务层发出的请求过多。控制器向服务层发出许多不返回数据的请求。控制器向服务层发出请求,而不传入参数。
目前,我正在使用Spring MVC开发一个Web应用程序,并且我有这样的方法来保存已更改用户的电子邮件:
/**
* <p>If no errors exist, current password is right and new email is unique,
* updates user's email and redirects to {@link #profile(Principal)}
*/
@RequestMapping(value = "/saveEmail",method = RequestMethod.POST)
public ModelAndView saveEmail(
@Valid @ModelAttribute("changeEmailBean") ChangeEmailBean changeEmailBean,
BindingResult changeEmailResult,
Principal user,
HttpServletRequest request){
if(changeEmailResult.hasErrors()){
ModelAndView model = new ModelAndView("/client/editEmail");
return model;
}
final String oldEmail = user.getName();
Client client = (Client) clientService.getUserByEmail(oldEmail);
if(!clientService.isPasswordRight(changeEmailBean.getCurrentPassword(),
client.getPassword())){
ModelAndView model = new ModelAndView("/client/editEmail");
model.addObject("wrongPassword","Password doesn't match to real");
return model;
}
final String newEmail = changeEmailBean.getNewEmail();
if(clientService.isEmailChanged(oldEmail, newEmail)){
if(clientService.isEmailUnique(newEmail)){
clientService.editUserEmail(oldEmail, newEmail);
refreshUsername(newEmail);
ModelAndView profile = new ModelAndView("redirect:/client/profile");
return profile;
}else{
ModelAndView model = new ModelAndView("/client/editEmail");
model.addObject("email", oldEmail);
model.addObject("emailExists","Such email is registered in system already");
return model;
}
}
ModelAndView profile = new ModelAndView("redirect:/client/profile");
return profile;
}
你可以看到我对服务层有很多请求,并且我从控制器重定向 - 这是业务逻辑。请显示此方法的更好版本。
还有另一个例子。我有这个方法,它返回用户的配置文件:
/**
* Returns {@link ModelAndView} client's profile
* @param user - principal, from whom we get {@code Client}
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "/profile", method = RequestMethod.GET)
public ModelAndView profile(Principal user) throws UnsupportedEncodingException{
Client clientFromDB = (Client)clientService.getUserByEmail(user.getName());
ModelAndView model = new ModelAndView("/client/profile");
model.addObject("client", clientFromDB);
if(clientFromDB.getAvatar() != null){
model.addObject("image", convertAvaForRendering(clientFromDB.getAvatar()));
}
return model;
}
方法转换AvaForRendering(clientFromDB.getAvatar())被放置在这个控制器的超类中,这是正确放置的方法,还是他必须放在服务层??
请帮忙,这对我来说真的很重要。