因此,对于一个学校项目,我们创建了一个网站,用户可以在其中提交有关水下生活等的报告。我们使用了简单的依赖注入 (javax.inject) 和错误检查模式,如下所示:
报告服务.java
public interface ReportService {
public static enum ReportServiceErrorsENUM {
DB_FAILURE, WRONG_COORD // etc
}
public Set<ReportServiceErrorsENUM> getLastErrors();
public int addNewReport(Report report);
}
ReportServiceImpl.java
public class ReportServiceImpl implements ReportService {
private Set<ReportServiceErrorsENUM> lastErrors;
private @Inject ReportDAO reportDAO;
@Override
public Set<ReportServiceErrorsENUM> getLastErrors() {
return this.lastErrors;
}
@Override
public int addNewReport(Report report) {
lastErrors= new HashSet<ReportServiceErrorsENUM>();//throw away previous errors
UserInput input = report.getUserInput();
if (input.getLatitude() == null) {
addError(ReportServiceErrorsENUM.WRONG_COORD);
}
// etc etc
if (reportDAO.insertReport(report) != 0) {
// failure inserting the report in the DB
addError(ReportServiceErrorsENUM.DB_ERROR);
}
if (lastErrors.isEmpty()) // if there were no errors
return EXIT_SUCCESS; // 0
return EXIT_FAILURE; // 1
}
}
提交报告控制器.java
@WebServlet("/submitreport")
public class SubmitReportController extends HttpServlet {
private static final long serialVersionUID = 1L;
private @Inject ReportService reportService;
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Report report = new Report();
// set the report's fields from the HttpServletRequest attributes
if(reportService.addNewReport(report) == ReportService.EXIT_FAILURE) {
for(ReportServiceErrorsENUM error : reportService.getLastErrors())
// display the errors etc
} else {
// display confirmation
}
}
}
这个想法是 Servlet 控制器调用服务(被注入)然后检查服务的返回值并在服务上调用 getLastErrors() 如果有错误 - 通知用户出了什么问题等等。现在我来了意识到这不是线程安全的 - @Inject'ed ReportService (reportService) 将由使用 servlet 的所有线程共享
- 是(交叉手指)吗?
- 如何改进这种错误机制?
谢谢