Thursday 15 August 2013

Spring Application Context in custom JSP Tag class

In this post I will explain how to retrieve Spring application context in custom JSP tag class. Lets assume you already have a tag configured in your Tag Library Descriptors file:

<tag>
    <name>myCustomTag</name>
    <tag-class>com.paulius.tags.MyCustomTag</tag-class>
    <body-content>empty</body-content>
</tag>

It is pretty straightforward to get Spring application context. All needs to be done is displayed in the below MyCustomTag class:

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

import java.io.IOException;

public class MyCustomTag extends SimpleTagSupport {

    @Override
    public void doTag()
            throws IOException {
        
        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(((PageContext) getJspContext()).getServletContext());
        YourBean yourBean = (YourBean) springContext.getBean("yourBeanName");
  
  yourBean.doSomething();
  
    }
 
}

JspContext is available from SimpleTagSupport class. JspContext is a parent class of PageContext which holds an instance of ServletContext needed to be passed to WebApplicationContextUtils#getWebApplicationContext(ServletContext) method to get actual Spring application context.

Once you have your Spring context available, you can get your beans by calling springContext.getBean("yourBeanName").