我遇到了 Freemarker 和 Velocity 的视图解析器(不在同一时刻运行)的问题——它们都没有看到 Spring 的会话 bean。Spring 的 InternalResourceViewResolver 效果很好。
一些代码:
<context:component-scan base-package="com.revicostudio.web" />
<mvc:annotation-driven />
<bean id="userSession" class="com.revicostudio.web.session.UserSession" scope="session" />
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/jsp/" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="layoutUrl" value="layout.jsp"/>
<property name="suffix" value=".jsp" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="requestContextAttribute" value="rc" />
</bean>
在jsp中:
${userSession}<br /> <!-- Null if Freemarker's view resolver active, session object if Spring's resolver active -->
${error}<br /> <!-- Normal request attribute, put to map, that works good in both resolvers -->
索引控制器:
@Controller
@RequestMapping("/index")
public class IndexController {
@RequestMapping(method=RequestMethod.GET)
public String getIndex(Model model) {
return "index";
}
@ModelAttribute("userRegisterCredentials")
public UserRegisterCredentials getUserRegisterCredentials() {
return new UserRegisterCredentials();
}
@ModelAttribute("userLoginCredentials")
public UserLoginCredentials getUserLoginCredentials() {
return new UserLoginCredentials();
}
}