Servlet to jsp communication best practice

徘徊边缘 提交于 2020-01-24 06:45:17

问题


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);

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>

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?


回答1:


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;
    }

}

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

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

See also:

  • Our Servlets wiki page
  • Our JSP wiki page
  • Our EL wiki page
  • How to avoid Java code in JSP files?


来源:https://stackoverflow.com/questions/12252579/servlet-to-jsp-communication-best-practice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!