Fork me on GitHub

RequestToViewNameTranslator

注意:所有文章除特别说明外,转载请注明出处.

第15章 RequestToViewNameTranslator

RequestToViewNameTranslator能够在处理器返回的view为空时使用其根据request获取viewName。SpringMVC提供的实现类只有:DefaultRequestToViewNameTranslator。

    public class DefaultRequestToViewNameTranslator implements RequestToViewNameTranslator {
    private static final String SLASH = "/";
    private String prefix = "";
    private String suffix = "";

    //该属性表示:如果其值与Slash不同则用于替换原来的分隔符Slash
    private String separator = "/";

    //该属性表示:如果前面的字符为Slash是否将其去掉
    private boolean stripLeadingSlash = true;

    //该属性表示:如果最后一个字符为Slash是否将其去掉
    private boolean stripTrailingSlash = true;

    //该属性表示:是否需要去掉扩展名
    private boolean stripExtension = true;

    private UrlPathHelper urlPathHelper = new UrlPathHelper();

    //这里分别添加了前缀和后缀
    public String getViewName(HttpServletRequest request) {
        String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
        return this.prefix + this.transformPath(lookupPath) + this.suffix;
    }
    //这里处理分隔符“,",“/"
    @Nullable
    protected String transformPath(String lookupPath) {
        String path = lookupPath;
        if (this.stripLeadingSlash && lookupPath.startsWith("/")) {
            path = lookupPath.substring(1);
        }

        if (this.stripTrailingSlash && path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }

        if (this.stripExtension) {
            path = StringUtils.stripFilenameExtension(path);
        }

        if (!"/".equals(this.separator)) {
            path = StringUtils.replace(path, "/", this.separator);
        }

        return path;
    }
}

UrlPathHelper属性参数

1.urlDecode:设置url是否需要编码,一般默认
2.removeSemicolonContent:设置是否删除url中与分号相关的内容
3.alwaysUseFullPath:设置是否总是使用完整路径

提示:因为urlPathHelper是用于处理url的工具,所以参数一般默认即可。

本文标题:RequestToViewNameTranslator

文章作者:Bangjin-Hu

发布时间:2019年10月15日 - 09:22:26

最后更新:2020年03月30日 - 08:17:03

原始链接:http://bangjinhu.github.io/undefined/第15章 RequestToViewNameTranslator/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Bangjin-Hu wechat
欢迎扫码关注微信公众号,订阅我的微信公众号.
坚持原创技术分享,您的支持是我创作的动力.