views:

42

answers:

2

I am using Spring MVC to develop a Java webapp. I have a setup as follows: 2 pages of the site are responsible for rendering similar content. One of the pages simply renders the items slightly differently (and hence would need a different view), and pulls the data slightly differently (with a limit on the query instead of pulling all the items).

My question is: would the best approach for this be to implement 2 separate controllers to handle each of these pages, or would it be better to use a single controller? If the answer is to use a single controller, how can I find out from inside the controller from what page the request came from (so that I can call the appropriate service and view)? Thanks

+1  A: 

With Spring 2.5+ annotated controllers, the difference between having one controller or two controllers is not especially relevant.

For example, say you have a controller class like this:

@Controller
public class MyController {

   @RequestMapping ("/pageA");
   public String handlePageA() {
      .. do stuff
   }

   @RequestMapping ("/pageB");
   public String handlePageB() {
      .. do stuff
   }
}

It should be obvious how this works. You get the benefit of one controller, with two handler methods, one for each "page".

There really is no reason to use pre-2.5 controllers any more. You can use the new style alongside the old one, so even legacy pre-2.5 apps can use the new style after an upgrade.

skaffman
Thanks. This is really nice. I am using Spring 3.0 but without annotations (I made this decision so that I could get a better grasp of what is actually going on). Without annotations, would the only solution be to use 2 controllers?
es11
Without annotations you would want to use a MultiActionController; you implement a method that can determine, given a request, which handler method to pass off to. But this situation is a good case for annotations.
JacobM
`MultiActionController` works, but it's an awfully ugly mechanism.
skaffman
A: 

You can approach the problem in different ways..
1. You can pass a special parameter which can help you decide which view to render, Following this way, you will need a write a single controller method with one extra param.
2. You can extract the common logic like db queries into a separate method and then use it in two controller methods, eliminating a most of the code duplication
3. This may not be applicable to you as both the views you are using are HTML, but just for information sake, you can use content negotiating resolver which can be used to write one controller do different views/rendering based on the content type.

Teja Kantamneni
How would I implement #1? Specifically, how can I pass a parameter to the controller?
es11
The Spring way to do #1 is to have two <bean> instances of the same controller class and set a <property> flag to different values in each, i.e. <property name="useSpecialQuery" value="true"/> in one
matt b