ViewResolver中的Spring-Mobile网站首选项不在每个控制器中 [英] Spring-mobile site preference in viewresolver not in each controller

查看:108
本文介绍了ViewResolver中的Spring-Mobile网站首选项不在每个控制器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 ?

(没有答案,通常spring config问题会有一些响应...我问过一个特别愚蠢的问题吗?)

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

推荐答案

您的问题对我来说似乎有效.我能想到的最直接的答案是拆分视图并利用文件夹名称中的网站首选项值:

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

(视图解析器的前缀应该为"/views/").

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

现在在控制器中您可以拥有:

Now in the controller you can have:

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

您不能使用两个单独的解析器,因为控制器无法决定使用哪个viewresolver,而只能决定使用哪个视图.

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

对于解析器的选择,只能通过"order"属性进行控制,而该属性完全超出了本使用案例的范围.

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

我感觉到代码气味在所有控制器方法中都重复了相同的逻辑.

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

因此,为了使该逻辑保持在一个位置,请尝试使用自定义的HandlerInterceptor,该自定义HandlerInterceptor将在postHandle方法中为视图名称添加前缀.您只需要根据request自己获取当前的SitePreference实例,这是完全可能的.

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.

这篇关于ViewResolver中的Spring-Mobile网站首选项不在每个控制器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆