我正在检查我的项目代码并在 Controller 中找到以下方法。在网上我发现controller
用于接收请求并提供响应。 Service
层用于业务逻辑,Dao
层用于数据CRUD相关操作。
在下面的方法中我可以看到业务逻辑。现在我不知道哪些代码应该移动到服务层或下面就可以了。
我正在审查代码,因此我需要提供评论,但我很困惑。
@RequestMapping(value = "/admin/app", method = RequestMethod.POST)
public ModelAndView saveApp(
@ModelAttribute("application") @Validated Application application,
BindingResult result) {
ModelAndView model = new ModelAndView();
ApplicationFormValidator formValidation = new ApplicationFormValidator();
boolean messageFlag = false;
String operationalStatus = null;
formValidation.validate(application, result);
if (result.hasErrors()) {
model.addObject(APPLICATION, application);
model.setViewName(ADD_APP);
} else {
if(checkActive(application)){
status = FormBeanValidator.encodeStatus(application.getStatus());
application.setStatus(status);
// calling service layer and convert model into entity
messageFlag = applicationService.addApp(application);
if (messageFlag) {
Application applicationForm = new Application();
applicationForm.setSuccessMessage(PropertyHandler.getPropertyInstance().getPropertyValue(Constants.SUCCESS_MESSAGE));
model.addObject(APPLICATION, applicationForm);
model.setViewName(ADD_APP);
} else {
application.setErrorMessage(PropertyHandler.getPropertyInstance().getPropertyValue(Constants.ERROR_MESSAGE));
model.addObject(APPLICATION, application);
model.setViewName(ADD_APP);
}
}
else{
application.setErrorMessage(PropertyHandler.getPropertyInstance().getPropertyValue(Constants.OTHER));
model.addObject(APPLICATION, application);
model.setViewName(ADD_APP);
}
}
return model;
}
最佳答案
代码看起来不错,但我建议进行一些修改:
1) 您的 checkActive(application)
似乎检查了有关您的业务对象(应用程序)的某些内容,因此将其移至服务层。您可以合并您的 checkActive()
方法逻辑,将 checkActive()
方法移至服务层,并在 applicationService.addApp(application)
中将其作为本地方法调用。
2) 您已在 if
和 else
block 中将 View 名称设置为相同。尝试将此代码移出 if-else block 因为它变得多余。
3) 通常只将所需的数据从 Controller 发送到 View 。这是通过创建 DTO(数据传输对象)并创建一个将业务对象字段映射到 DTO 的转换器类来完成的。可以查看 DTO here 的示例用例
关于java - Spring : Controller and Service Layer coding standard example,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27353741/