Servlet与JSP通讯的最佳实践 [英] Servlet to jsp communication best practice

查看:62
本文介绍了Servlet与JSP通讯的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何在Google App Engine上编写Java Servlet和JSP页面.我正在尝试使用MVC模型,但不确定自己是否做对了.当前,我有一个servlet,在访问页面时会调用它. servlet完成所有处理,并创建一个HomePageViewModel对象,将其转发给jsp,如下所示:

I'm learning how to write java servlets and jsp pages on google app engine. I'm attempting to use an MVC model but I'm not sure if I'm doing it right. Currently, I have a servlet that is called when a page is accessed. The servlet does all the processing and creates a HomePageViewModel object that is forwarded to the jsp like this:

// 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方面,我有这样的东西:

Over on the jsp side, I have something like this:

<%@ 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数据?

So my question is two fold. First, is this a reasonable way to do things for a small webapp? This is just a small project for a class I'm taking. And second, in the jsp file, is there a better way to access the viewmodel data?

推荐答案

如果您遵守 Java规范(即,将私有属性与公共getter/setter一起使用),

If you adhere the Javabeans spec (i.e. use private properties with public getters/setters),

public class HomePageViewModel {

    private String test;

    public String getTest() { 
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }

}

然后,您可以只使用EL(表达语言)来访问数据.

then you can just use EL (Expression Language) to access the data.

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

另请参见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆