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:


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 javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;


public class MyCustomTag extends SimpleTagSupport {

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

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").

No comments:

Post a Comment

Note: only a member of this blog may post a comment.