我的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 。请帮忙。
答案 0 :(得分:2)
你得到了什么:
Controller
返回一个空视图名称,因此DefaultRequestToViewNameTranslator
从servlet路径生成一个URI = path而没有斜杠和文件扩展名: resources / myfilename
BeanNameViewResolver
尝试从名为 resources / myfilename 的上下文中获取View
,似乎失败并链接到下一个ViewResolver
InternalResourceViewResolver
返回JstlView
指向jsp前缀+ viewName + suffix = /WEB-INF/jsp/resources/myfilename.jsp
所以BeanNameViewResolver
似乎没有解析视图,InternalResourceViewResolver
的返回是预期的。
你想要什么(我想)
您想要从默认视图名称中删除文件名,而不仅仅是扩展名。
RequestToViewNameTranslator
并在DispatcherServlet
上下文中声明名称 viewNameTranslator 。例如:
public class StripFileNameViewNameTranslator extends DefaultRequestToViewNameTranslator {
@Override
protected String transformPath(String lookupPath) {
String path = super.transformPath(lookupPath);
return StringUtils.substringBeforeLast(path, "/");
}
}