I am learning how to write java servlets and jsp pages in the google engine. I'm trying to use the MVC model, but I'm not sure if I am doing this correctly. I currently have a servlet that gets called when accessing the page. The servlet does all the processing and creates a HomePageViewModel object, which is passed to jsp as follows:
// 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);
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 twofold. Firstly, is this a smart way to do something for a small webapp? This is just a small project for the class I am taking. And secondly, is there a better way in jsp file to access viewmodel data?
source share