我一直在从一本书上读到有关 MVC 的内容。令人困惑的是 View 到模型通信是如何发生的。我想了解在使用 JSP 和 servlet 的简单 Java Web 应用程序中这是如何发生的。
the view usually gets the state and data it needs to display, directly from the model
它是改变模型对象状态的 Controller 。一旦更改, Controller 就会通过请求对象将该特定对象传递到 JSP 页面。
在 Controller servlet 中
rd = request.getRequestDispatcher("/success.jsp");
User userObj = new User(username, password);
request.setAttribute("user", userObj);
rd.forward(request, response);
成功.jsp
<%
User bean=(User)request.getAttribute("user");
out.print("Welcome, "+bean.getName());
%>
请求调度程序将请求和响应对象转发到 jsp 页面。 jsp 页面使用请求对象来访问修改后的模型对象 (userObj)。这就是 View 与模型对话的意思吗?这是 View 和模型之间通信的基本方式吗? (我的意思是通过 request.getAttribute()
?)
最佳答案
在 MVC 架构中, Controller 从请求对象接收数据,操作模型,然后将流程转发到 jsp。 Jsp 从设置并显示属性的范围中获取。
您可以在多个范围内设置该属性。
Request, Session, ServletContext
每个范围都有 getAttribute()
和 setAttribute()
${requestScope.yourValue} : request scope which is also the default
${sessionScope.yourValue} : retrieving from the session scope
${applicationScope.yourValue} : retrieving from the context scope
当 JSP 从各自的范围中获取值时,这是 View 与模型对话的示例。此外,您并不强制要求遵循此流程,您始终可以根据您的要求自定义应用程序的流程。
关于java - MVC 中 View 与模型的通信如何发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30010323/