集成 Spring Beans 和 JSP 标签

Integrate Spring Beans and JSP Tags

是否可以在 Spring 中以某种方式集成 Spring beans 和 JSP 标签。那就是使用 Spring bean 作为 JSP 标签?如果是这样,这是 good/terrible 的想法吗?所以这样的事情是可能的:

@Component
public class SomeBean extends SimpleTagSupport {

    @Autowired
    SomeBean someBean;

    @Override
    public void doTag() throws JspException, IOException {
        getJspContext().getOut().write(someBean.doSomething());
    }
}

我要在 tags.tld 中做什么才能让它使用 Spring bean 而不是创建一个没有注入 someBean 的新实例?还是其他原因?

InternalResourceViewResolver 允许您使用 exposition 将 bean 导出到 jsp 上下文中。例如,如果你想公开 beans 列表,你应该在 dispatcher-servlet.xml 下配置视图解析器:

   ...
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/views/"/>
       <property name="suffix" value=".jsp"/>
       <property name="exposedContextBeanNames">
           <list>
               <value>someBean</value>
           </list>
       </property>
   </bean>
   ...

其中 someBean 是您要导出到 jsp 上下文的 bean 的名称。你甚至可以公开 all spring beans:

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

这允许您通过 bean 的名称从 jsp 上下文访问 spring bean。

假设您的标签处理程序如下所示:

package com.mytags;
public class SomeTag extends SimpleTagSupport {

    private SomeBean bean;

    @Override
    public void doTag() throws JspException, IOException {
        getJspContext().getOut().write(bean.doSomething());
    }

    public SomeBean getBean(){...}
    public void setBean(SomeBean bean){...}
}

然后在 tld 中,您的标签将以下列方式描述:

...
<tag>
    <name>someTag</name>
    <tag-class>com.mytags.SomeTag</tag-class>
    <body-content>empty</body-content>
    <attribute>
        <name>bean</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
        <type>com.mybeans.SomeBean</type>
    </attribute>
</tag>
...

请注意,您必须将 rtexprvalue 指定为 true,因为您会将 bean 作为 EL 表达式传递到标记中。现在您可以在 jsp:

中使用此标签
<%@ taglib prefix="mytags" uri="http://mytags.com" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>
    <mytags:someTag bean="${someBean}"/>
  </body>
</html>

但实际上直接从标记的处理程序访问 spring bean 并不是一个好主意。 Tag 必须知道如何显示数据,但应该抽象出如何获取这些数据。最好准备好所有你想在控制器中显示的数据,并将其作为模型传递给 jsp.