【问题标题】:Servlet to jsp communication best practiceServlet 到 jsp 通信的最佳实践
【发布时间】:2012-08-28 11:16:01
【问题描述】:

我正在学习如何在谷歌应用引擎上编写 java servlet 和 jsp 页面。我正在尝试使用 MVC 模型,但我不确定我是否做得对。目前,我有一个在访问页面时调用的 servlet。 servlet 完成所有处理并创建一个 HomePageViewModel 对象,该对象被转发到 jsp,如下所示:

// Do processing here
// ...
HomePageViewModel viewModel = new HomePageViewModel();
req.setAttribute("viewModel", viewModel);

//Servlet JSP communication
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/jsp/home.jsp");
reqDispatcher.forward(req, resp);

在 jsp 方面,我有这样的事情:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="viewmodels.HomePageViewModel" %>
<%
  HomePageViewModel viewModel = (HomePageViewModel) request.getAttribute("viewModel");
  pageContext.setAttribute("viewModel", viewModel);
%>

<html>
  <body>
  <% out.println(((HomePageViewModel)pageContext.getAttribute("viewModel")).Test); %>
  </body>
</html>

所以我的问题有两个方面。首先,对于小型 Web 应用来说,这是一种合理的处理方式吗?这只是我正在上课的一个小项目。其次,在jsp文件中,有没有更好的方式来访问viewmodel数据?

【问题讨论】:

    标签: model-view-controller jsp servlets


    【解决方案1】:

    如果您遵守 Javabeans spec(即使用公共 getter/setter 的私有属性),

    public class HomePageViewModel {
    
        private String test;
    
        public String getTest() { 
            return test;
        }
    
        public void setTest(String test) {
            this.test = test;
        }
    
    }
    

    那么您可以只使用 EL(表达式语言)来访问数据。

    <%@ page pageEncoding="UTF-8" %>
    <html>
      <body>
      ${viewModel.test}
      </body>
    </html>
    

    另见:

    【讨论】:

      猜你喜欢
      • 2016-10-26
      • 1970-01-01
      • 2013-12-21
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 2017-01-22
      • 2015-07-23
      相关资源
      最近更新 更多