日期:2014-05-19  浏览次数:20737 次

Jsp自定义标签访问struts2+spring+hibernate问题
我想使用Jsp自定义标签来通过struts2+spring+hibernate框架来访问数据库,在struts2+spring+hibernate中通过如下代码访问数据库:
Java code
public class TestAction extends ActionSupport{
    ......
    WebApplicationContextUtils.getRequiredWebApplicationContext().getBean("testDao");
}

上面的代码在struts2+spring+hibernate中运行很正常。

现在我想通过Jsp自定义标签来访问struts2+spring+hibernate框架,从而获得数据,代码如下:
Java code
public class TestTag extends TagSupport{
   public int doStartTag() throws JspException{
       ......
       WebApplicationContextUtils.getRequiredWebApplicationContext().getBean("testDao");
   }
}


当我运行这个JSP自定义标签时,系统出错:
Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException

WebApplicationContextUtils.getRequiredWebApplicationContext().getBean("testDao");//引起空指针异常

有什么办法能使用JSP自定义标签来访问struts2+spring+hibernate框架来获得数据?

------解决方案--------------------
给你个例子
Java code

public class XxxTag extends RequestContextAwareTag {
  //覆盖doStartTagInternal方法
  protected int doStartTagInternal() throws Exception {
      this.getRequestContext().getWebApplicationContext().getBean("beanName");
      
  }
}

------解决方案--------------------
在标签中可以通过pageContext得到servletContext
Java code
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
XxxService service = (XxxService)ctx.getBean("beanName");