springmvc動態切換views目錄實現多套jsp頁面的國際化
mvc重要配置一般情況都會這樣控制jsp頁面的字首和字尾,但是不包含cache屬性
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 預設springmvc會把modelandview的jsp位置快取,必須設定禁用快取否則無法動態切換目錄 --> <property name="cache" value="false"></property> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean>
攔截器類 import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver;
public class JspDirFilter extends HandlerInterceptorAdapter { @Autowired private InternalResourceViewResolver internalResourceViewResolver; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String language = request.getParameter("language"); if(!StringUtils.isEmpty(language)) { //預設springmvc會把modelandview的jsp位置快取,必須設定禁用快取否則無法動態切換目錄,已經通過配置檔案設定 //internalResourceViewResolver.setCache(false); internalResourceViewResolver.setPrefix("/WEB-INF/views/"+language+"/"); Cookie cookie = new Cookie("language", language); response.addCookie(cookie); }else {//如果沒有傳參則根據cookie設定語言 Cookie[] cookies = request.getCookies(); for (Cookie c : cookies) { if(c.getName().equals("language")) { internalResourceViewResolver.setPrefix("/WEB-INF/views/"+c.getValue()+"/"); } } } return super.preHandle(request, response, handler); } }
配置攔截器
<mvc:interceptors> <bean class="net.appdd.web.filter.JspDirFilter"></bean> </mvc:interceptors>
整個功能就配置這三個地方就可以了
開始做動態切換的時候並沒有加<property name="cache" value="false"></property>這行,導致無論如何setPrefix之後都不生效,debug原始碼發現是cache導致的,spmvc預設是開啟了modelandview快取的,多次請求同一個requestMapping會從快取中獲取modelandview,而不是重新根據prefix生成