xingyu
xingyu

Reputation: 332

View Models in Servlets / MVC

I am building an application with simple Servlets and the MVC pattern. I am not using any framework like Spring.

I have some Model classes like this:

public class BlogPost {

private List<Comment> _comments;

// Things
}

and

public class Comment {
// Code
}

Posts can have zero or more comments associated with them in that collection.

However, I want to attach some additional information to the BlogPost Model before it is passed to the View, namely a value I set in a Cookie once a user makes a comment on a BlogPost. Strictly speaking, this is not a part of the BlogPost Model itself -- it is unrelated, incidental information, however I am not sure if I should make it easy on myself and just add it to the BlogPost class or do something to abstract this out a bit more.

So, should I add a field to the BlogPost class to handle this additional value, OR should I make a "View Model" along the lines of this which gets passed to the JSP view:

public class BlogPostView {

public BlogPostView(BlogPost bp, String message) {
  // Constructor stuff, save these to instance variables
}

public BlogPost getBlogPost() { /* ... */ }
public String getMessage() { /* ... */ }

}

Upvotes: 0

Views: 251

Answers (2)

stephen.hanson
stephen.hanson

Reputation: 9624

If BlogPost and your cookie data are unrelated, it is a bad idea to put the cookie data in your BlogPost class. The BlogPost class should represent what it's called - a blog post. It would be confusing to have other data associated.

Your second option of creating a class specifically to pass to the view is a better idea, though I'm curious to know why you need to pass the blog post and the cookie data as one object to your view? If you're using raw servlets:

request.setAttribute("blogPost",blogPost);
request.setAttribute("cookieData",cookieData);

Using a model class (e.g. Spring MVC ModelMap):

model.addAttribute("blogPost",blogPost);
model.addAttribute("cookieData",cookieData);

Your view will have access to both pieces of data, which you can manipulate using JSTL or other tag libraries.

If there's something I'm missing, can you elaborate more?

Upvotes: 1

kkumar
kkumar

Reputation: 355

Create a HashMap model - and pass it along with the response to view. model.put("blog", blog) model.put("message", "some message")

Upvotes: 0

Related Questions