3

我的 servlet-context 文件有

<beans:bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <beans:property name="useNotAcceptableStatusCode"
        value="false" />
    <beans:property name="contentNegotiationManager">
        <beans:bean
            class="org.springframework.web.accept.ContentNegotiationManager">
            <beans:constructor-arg>
                <beans:bean
                    class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
                    <beans:constructor-arg>
                        <beans:map>
                            <beans:entry key="html" value="text/html" />
                            <beans:entry key="json" value="application/json" />
                        </beans:map>
                    </beans:constructor-arg>
                </beans:bean>
            </beans:constructor-arg>
        </beans:bean>
    </beans:property>

    <beans:property name="viewResolvers">
        <beans:list>
            <beans:bean
                class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
            <beans:bean id="jspView"
                class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <beans:property name="prefix" value="/WEB-INF/jsp/" />
                <beans:property name="suffix" value=".jsp" />
            </beans:bean>
        </beans:list>
    </beans:property>

    <beans:property name="defaultViews">
        <beans:list>
            <beans:bean
                class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
        </beans:list>
    </beans:property>
</beans:bean>

我的控制器文件有

@Controller("resources")
public class Resources {

     @RequestMapping(value = "/resources/{name}", method = RequestMethod.GET)
     public Map getResource(@PathVariable String name) {
        return new HashMap();
     }
}

但是每当我尝试访问/server/resources/myfilename.html

服务器抛出 404 说/server/WEB-INF/jsp/resources/myfilename.jsp未找到。但它应该使用 BeanNameViewResolver加载/server/WEB-INF/jsp/resources.jsp 。请帮忙。

4

1 回答 1

2

你得到什么:

  • Controller返回一个空视图名称,因此DefaultRequestToViewNameTranslator从 URI = path from servlet path 生成一个,不带斜杠和文件扩展名:resources/myfilename

  • BeanNameViewResolver尝试View从名为resources/myfilename的上下文中获取一个,似乎失败并链接到下一个ViewResolver

  • InternalResourceViewResolver返回一个JstlView指向jsp前缀+viewName+后缀= /WEB-INF/jsp/resources /myfilename.jsp

所以BeanNameViewResolver似乎不解决视图和返回InternalResourceViewResolver是预期的。

你想要什么(我认为)

您想从默认视图名称中删除文件名,而不仅仅是扩展名。

  • 实现 a并在名为viewNameTranslatorRequestToViewNameTranslator的上下文中声明它。DispatcherServlet

例如:

public class StripFileNameViewNameTranslator extends DefaultRequestToViewNameTranslator {

    @Override
    protected String transformPath(String lookupPath) {
        String path = super.transformPath(lookupPath);
        return  StringUtils.substringBeforeLast(path, "/");
    }
}
于 2013-05-15T19:14:40.690 回答