理解視圖解析
控制器方法和視圖的實(shí)現(xiàn)會(huì)在模型內(nèi)容上達(dá)成一致涂屁,這是兩者的最大關(guān)聯(lián)书在,除此之外,兩者應(yīng)該保持足夠的距離。
創(chuàng)建JSP視圖
1、**InternalResourceViewResolver 將視圖解析為InternalResourceView
(1)使用@Bean配置InternalResourceViewResolver **視圖解析器
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
(2)作為替代方案丑瞧,使用基于XML的Spring配置**InternalResourceViewResolver **視圖解析器
<bean id="viewResolver"
class ="org.springframework.web.servlet.view.
InternalResourceViewResolver"
p:prefix="/WEB-INF/views"
p:suffix=".jsp"/>
InternalResourceViewResolver配置就緒之后茸俭,它就會(huì)將邏輯視圖名解析為JSP文件。當(dāng)邏輯視圖名包含斜線時(shí)仔拟,這個(gè)斜線也會(huì)帶到資源的路徑名中,因此它會(huì)對(duì)應(yīng)到prefix屬性所引用目錄的子目錄下的JSP文件。
2甚垦、InternalResourceViewResolver 將視圖解析為JstlView,只需設(shè)置它的viewClass屬性即可
(1)使用@Bean配置**InternalResourceViewResolver **視圖解析器
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(
org.springframework.web.servlet.view.JstlView.class);
return resolver;
}
(2)使用基于XML的Spring配置
<bean id="viewResolver"
class ="org.springframework.web.servlet.view.
InternalResourceViewResolver"
p:prefix="/WEB-INF/views"
p:suffix=".jsp"
p:viewClass="org.springframework.web.servlet.view.JstlView"/>