在工业界,我们都是为了简单。例如,对于从浏览器到服务器再到持久性存储(数据库)的用户交互,我们遵循这些方法。
首先是MVC 模式。这将允许我们完全不为从浏览器到服务器的每个用户交互编写一个 Servlet。这允许我们做以下事情:
- 允许控制器处理用户请求并将其链接到我们的用户操作(我们的模型)。该模型允许我们编写业务逻辑来响应用户数据。
在当今的 Java 世界中,存在满足我们 MVC 要求的框架。出现在 Java 框中的是JSF(JavaServer Faces)。
对于后端,我们肯定使用数据库,但我们也很聪明,使用ORM(对象关系映射)将我们的现实问题建模为对象模型,以及如何最好地保存(存储)这些对象模型。有的使用ERM(Entity-Relational Modelling)来设计语义数据模型。
在中间,业务逻辑,我们添加一个服务(作为业务逻辑层)不想关心在哪里读/写数据,只要他们能看到它想要的数据。为此,添加了一个服务层来促进这一点。本质上我们有这种效果。
public class ActionServlet extends HttpServlet {
//Action registration
public void init() {
ActionMapping mapping = .....; //some instatiation
mapping.setAction("/userRegistration", UserRegistrationAction.class);
//Save it in Application Scope
getServletContext().setAttribute("actionConfig", mapping);
}
private void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
String path = request.getPathInfo();
Action action = ((ActionMapping)getServletContext().getAttribute("actionConfig")).getAction(path);
if (action == null) {
throw new Exception("No action of '" + path + "' found.");
}
action.execute(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
doAction(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
doAction(request, response);
}
}
public abstract class Action {
public abstract void execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
protected void dispatch(HttpServletRequest request, String path) {
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
}
}
public class UserRegistrationAction extends Action {
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
//Business Logic goes here...
//Call DAO,
UserRegistrationDAO dao = ; //Some DAO instantation
User user = createUserFromForm(request);
dao.save(user);
dispatch(request, "success");
}
}
关于持久性,Java 5 及更高版本带有JPA。您可以使用任何形式的 ORM,具体取决于您的项目范围。有 Hibernate(它也支持 JPA),或者如果您愿意,可以编写自己的 DAO。
还有一点,将所有这些过程粘合在一起很乏味。幸运的是,我们有框架可以帮助我们更轻松地制作上面的漂亮示例。像JBoss Seam 这样的框架就是这样做的,它完全使用Java 规范。现在,选择简单的设计模型和 MVC(用于学习目的)。当您习惯了架构后,请使用框架。