mvc - model view controller
Code for this page is at :
https://github.com/gnurmatova/jersey-mvc-jstl-scopes
MVC Pattern stands for Model-View-Controller Pattern. MVC takes the business logic out of the servlet and puts it in a "Model" - a reusable plain old java class. The model is a combination of the business data and the methods to operate that data.
https://github.com/gnurmatova/jersey-mvc-jstl-scopes
MVC Pattern stands for Model-View-Controller Pattern. MVC takes the business logic out of the servlet and puts it in a "Model" - a reusable plain old java class. The model is a combination of the business data and the methods to operate that data.
- Model (POJO) - Holds the real business logic and the state. In other words, it knows the rules for getting and updating the state.
- View (JSP) - View represents the visualization of the data that model contains. It gets the state of the model from controller. It's also the part that gets the user input that goes back to the controller.
- Controller (Servlet) - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.
jersey mvc
Jersey provides an MVC implementation mechanism. To enable it, add dependency:
<dependency> <groupId>org.glassfish.jersey.ext</groupId> <artifactId>jersey-mvc-jsp</artifactId> <version>2.14</version> </dependency>
and an init parameter in your web.xml file:
<init-param> <param-name>jersey.config.server.provider.classnames</param-name> <param-value>org.glassfish.jersey.server.mvc.jsp.JspMvcFeature</param-value> </init-param>
Now you should be able to use Viewable class to redirect to the items in your WebContent folder:
@GET @Path("mvc") public Viewable index() { return new Viewable("/index.jsp"); }
You can also pass data to your model:
@GET
@Path("mvc/model")
public Response mvcModel() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("user", "Gula");
List<Song> songList = new ArrayList<Song>();
ListSongsCommand cmd = new ListSongsCommand();
songList = cmd.execute();
map.put("songs", songList);
return Response.ok(new Viewable("/model", map)).build();
}
to process the data passed to jsp, use:
<title>Passing Model to MVC example</title>
</head>
<body>
<h1>you are logged in as ${it.user}!</h1>
<p>
songs available in the store :<br />
<% HashMap<String, Object> it = (HashMap<String, Object>)pageContext.findAttribute("it");
for(Song song : (ArrayList<Song>)it.get("songs")){
out.println("<br><b>"+song.getTitle()+"</b> by <i>"+song.getArtist()+"</i>");
}
%>
</p>
</body>