java - MVC 中 View 与模型的通信如何发生

标签 java jsp servlets model-view-controller

我一直在从一本书上读到有关 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/

相关文章:

java - Eclipse Web 工具项目是否处理 JSP 内部的重构?

java - 在 servlet 响应中使用 Printwriter

java - 使用 Mockito 使用 @Value 时如何模拟 map

java - 如果不存在则插入mysql条目,如果存在则更新java

java - 如何使用 java.util.Formatter 将 double 格式化为千位分隔和 2 位小数

java - NullPointerException 尝试设置index.jsp

java - 如何将 HttpServletRequest 的 ParameterMap 转换为 Java 中的 bean

java - 大约 10-20 分钟不活动后,与 mysql 服务器的 JDBC 连接失败

java - 如何使用 servlet 运行 Freemarker 模板?

apache - tomcat 7 taglib规范版本不一致