MVC 中如何进行视图模型通信

How view to model communication happens in MVC

我一直在从一本书中读到有关 MVC 的内容。混淆是关于模型通信的视图如何发生的事实。我想了解在使用 JSP 和 servlet 的简单 java Web 应用程序中这是如何发生的。

the view usually gets the state and data it needs to display, directly from the model

它是改变模型对象状态的控制器。一旦更改,控制器就会通过请求对象将该特定对象传递给 JSP 页面。

在控制器 servlet 中

rd = request.getRequestDispatcher("/success.jsp");
User userObj = new User(username, password);
request.setAttribute("user", userObj); 
rd.forward(request, response);

在success.jsp

<%  
User bean=(User)request.getAttribute("user");  
out.print("Welcome, "+bean.getName());  
%>  

请求调度程序将请求和响应对象转发到 jsp 页面。 jsp 页面使用请求对象来访问修改后的模型对象 (userObj)。这是视图与模型对话的意思吗?这是视图和模型之间的基本通信方式吗? (我是说通过request.getAttribute()?)

在 MVC 架构中,控制器从请求对象接收数据,操纵模型,然后将流转发到 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 从各自的范围中获取值时,这是视图与模型对话的示例。此外,您并非必须遵守此流程,您始终可以根据您的要求自定义应用流程。