Showing posts with label servletContext. Show all posts
Showing posts with label servletContext. Show all posts

Friday, September 19, 2014

Access Spring-ApplicationContext/ServletContext From Everywhere

Create a java class such named 'AppUtils.java' with following contents:


package com.pkm.maven.common;

import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class AppUtils implements ApplicationContextAware {
    private static ApplicationContext ctx;
    private static ServletContext __servletContext;
    
    @Override
    public void setApplicationContext(ApplicationContext ctx) {
        AppUtils.ctx = ctx;
    }
    
    public static ApplicationContext getApplicationContext() {
        return ctx;
    }
    
    public static ServletContext getServletContext() {
        if (__servletContext == null) {
            __servletContext = (ServletContext) ctx.getBean("servletContext");
        }
        return __servletContext;
    }
}

Now make a entry to 'applicationContext.xml'


<bean id="contextApplicationContextProvider" class="com.pkm.maven.common.AppUtils"></bean>

Finally access application context/servlet context from everywhere like this:

package com.pkm.maven.app;

import com.pkm.maven.common.AppUtils;
import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;

public class AppHandler {
    
    public static String getContextPath() {
        try {
            ApplicationContext applicationContext = AppUtils.getApplicationContext();
            ServletContext servletContext = AppUtils.getServletContext();
            return servletContext.getContextPath();
        }
        catch (Exception ex) {
            return "<b>ERROR</b>";
        }
    }
}

Sunday, December 8, 2013

Getting Request , Response & ServletContext in the Grails service class

import org.codehaus.groovy.grails.web.util.WebUtils;

Getting current request object:
def request = WebUtils.retrieveGrailsWebRequest().getCurrentRequest();

Getting response object:
def response = WebUtils.retrieveGrailsWebRequest().getCurrentResponse();

Getting servletContext object:
def servletContext = WebUtils.retrieveGrailsWebRequest().getServletContext();