4

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?

ConditionRacer
  • 4,418
  • 6
  • 45
  • 67

1 Answers1

7

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555