Spring controller setup question?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 02:00:15

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2203066/spring-controller-setup-question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!