Best servlet messaging with jsp

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?

+4
source share
1 answer

If you stick with 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:

+7
source

Source: https://habr.com/ru/post/1432130/


All Articles