【问题标题】:how to inject userContext in JSP pages如何在 JSP 页面中注入 userContext
【发布时间】:2015-08-04 13:14:47
【问题描述】:

如何在 jsp 文件中检索上下文的值?本教程非常适合我的需要,但我需要检索 jsp 文件中的属性值。

http://www.mkyong.com/spring/spring-listfactorybean-example/

有没有我可以使用的特定拦截器?

【问题讨论】:

    标签: spring-mvc localization


    【解决方案1】:

    你指的是spring上下文对吗?

    一般来说,JSP 应该只是页面的模板,因此与后端的唯一交互应该是访问作用域属性的值。这意味着您需要的任何 bean 值都应该存储在模型中。

    话虽这么说,有几种方法可以公开 Spring bean 以供查看。取决于您使用的视图解析器,扩展 UrlBasedViewResolver 的解析器具有 setExposeContextBeansAsAttributes 属性

    设置是否在应用上下文中制作所有的Spring bean 可作为请求属性访问,通过一次延迟检查 属性被访问。这将使所有此类 bean 在 JSP 2.0 页面以及 JSTL 的 c:out 中的普通 ${...} 表达式 值表达式。

    默认为“假”。

    你可以像这样配置它

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
        <property name="exposeContextBeansAsAttributes" value="true" />
    </bean>
    

    【讨论】:

      【解决方案2】:

      userContext 的 bean(或源代码)注入您的控制器,以便您可以在局部变量中访问它。

      所以举个例子可能是这样的:

      @Autowired
      private CustomerBean customerBean;
      
      @RequestMapping(value="/foobar/index.jsp")
      public String (HttpServletRequest request) {
      Object userContext = customerBean.getLists();
      request.setAttribute("userContext", userContext);
      return "/foobar/index.jsp";  // expecting JstlView viewResolver to map to JSP file
      }
      

      在 CONTROLLER 中只需将数据添加到 HttpServletRequest(您只需将其作为参数添加到方法中以引入它)。

      然后使用request.setAttribute("userContext", userContext); 然后在JSP 中使用${userContext} 之类的表达式语言简单地访问它。还有其他使用 Spring 模型范式的方法,但它们有效地完成了上述工作。

      确保您的 JstlView 设置为 https://dzone.com/articles/exploring-spring-controller

      有关如何在 JSP 中使用 EL 来检索附加到请求的数据的更多信息: How to obtain request / session / servletcontext attribute in JSP using EL?

      【讨论】:

        猜你喜欢
        • 2015-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多