Spring-mobile site preference in viewresolver not

2019-07-12 02:17发布

问题:

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.