我试图将控制器限制在与验证http参数相关的工作,决定使用哪些参数调用什么服务方法,将什么放入httpsession或请求中,重定向或转发到哪个视图等类似于web的事情。
红旗警告:如果Controller滥用Service层,则我的Controller架构可能出现问题。
Controller对Service层发出太多请求。控制器向Service层发出许多不返回数据的请求。控制器在不传递参数的情况下向Service层发出请求。
目前,我正在使用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;
}
这个控制器的超类中放置了一个名为convertAvaForRendering(clientFromDB.getAvatar())的方法,这个方法是否放置得当?或者他必须被放在服务层中?
请帮忙看一下,对我来说真的很重要。