2

我遇到了 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();
    }
}
4

1 回答 1

1

1.您应该注释控制器以指出应在会话中公开哪个模型属性 2.在 freemarker 中,对会话属性的访问由 freemarker 会话包装器完成。

下面的简短示例,基于您的代码:

@Controller
@SessionAttributes("userRegisterCredentials")
@RequestMapping("/index")
public class IndexController {
    @RequestMapping(method=RequestMethod.GET)
    public String getIndex(Model model) {
        return "index";
    }

    @ModelAttribute("userRegisterCredentials")
    public UserRegisterCredentials getUserRegisterCredentials() {
        return new UserRegisterCredentials();
    }    

}

在 ftl 方面:${Session.userRegisterCredentials.someStringField}

于 2014-12-09T14:10:25.637 回答