Spring-mobile site preference in viewresolver not in each controller

倖福魔咒の 提交于 2019-12-11 02:29:29

问题


The spring mobile documentation shows how to implement a separate mobile view layer like below :

@Controller
public class HomeController {

    @RequestMapping("/")
    public String home(SitePreference sitePreference, Model model) {
        if (sitePreference == SitePreference.MOBILE) {
            // prepare mobile view for rendering
            return "home-mobile";
        } else {
            // prepare normal view for rendering
            return "home";
        }
    }
}

However, I would prefer to apply the different view name(prefixing it with a folder), in the view resolver. How would I do this ?

(edit : No answers, normally spring config issues have a few responses ... have I asked a particularly stupid question ?)


回答1:


Your question seems valid to me. The most straight-forward answer that I can think of is having the views splitted and make use of the site preference value in the folder name:

/views/normal/home.jsp
/views/mobile/home.jsp

(The view resolver's prefix should be "/views/", of course).

Now in the controller you can have:

return sitePreference.name().toLowerCase() + "/home";

You cannot use two separate resolvers, as the controller cannot decide which viewresolver to use, but only which view.

As for the resolver selection, that can only be controlled via the "order" property which is completely out of scope for this use case.


Edit: I sensed the code smell in having the same logic duplicated in all the controller methods.

So, in order to keep that logic in one place, try to make use of a custom HandlerInterceptor which would add the prefix to the view name in the postHandle method. You only need to grab the current SitePreference instance yourself, based on the request , which should be perfectly possible.



来源:https://stackoverflow.com/questions/8433274/spring-mobile-site-preference-in-viewresolver-not-in-each-controller

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