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>";
        }
    }
}

Wednesday, September 17, 2014

Spring MVC with ControllerClassNameHandlerMapping MultiActionController


maven2-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:component-scan base-package="com.pkm.maven"/>
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        <property name="caseSensitive" value="true" />
        <!--<property name="pathPrefix" value="/pathPrefix" />-->
    </bean>
    <bean class="com.pkm.maven.controller.CustomerController"/>

    <bean id="viewResolver"
    	class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
        <property name="viewClass">
            <value>com.pkm.maven.common.JstlView</value>
        </property>
    </bean>
</beans>

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>maven2</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>maven2</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

CustomerController.java


package com.pkm.maven.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
 
public class CustomerController extends MultiActionController{
 
    public ModelAndView method1(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        return new ModelAndView("CustomerPage", "msg", "method1() method"); 
    }
 
    public ModelAndView method2(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        return new ModelAndView("CustomerPage", "msg", "method2() method"); 
    }
}

You have to create a file named 'CustomerPage.jsp' under WEB-INF/jsp/

URL would be like this

  • customer/method1.htm
  • customer/method2.htm

Download example src code

Sunday, September 14, 2014

Spring MVC Framework Global Layout Used To Be Template

In your xxxxx-servlet.xml you can extend the viewResolver viewClass with your own implementation (Download full source code)


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        <property name="caseSensitive" value="true" />
        <!--<property name="pathPrefix" value="/pathPrefix" />-->
    </bean>


    <bean class="com.pkm.controllers.UserController"/>
    
    <bean id="viewResolver"
     class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
        <property name="viewClass">
            <value>com.pkm.common.JstlView</value>
        </property>
    </bean>

</beans>

JstlView.java

package com.pkm.common;

import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.InternalResourceView;

public class JstlView extends InternalResourceView {
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String dispatcherPath = prepareForRendering(request, response);
        if (model != null) {
            for (Map.Entry pairs : model.entrySet()) {
                String key = pairs.getKey().toString();
                Object value = pairs.getValue();
                request.setAttribute(key, value);
            }
        }

        // set original view being asked for as a request parameter
        request.setAttribute("_____CONTROLLER_VIEW_NAME_____", dispatcherPath);

        // force everything to be template.jsp
        RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/template.jsp");
        rd.include(request, response);
    }
}

template.jsp


<!doctype html>
<html lang="en">
<head>
    <title>Hello :: Spring Application</title>
</head>
<body>
    <header>
        <jsp:include page="header.jsp"/>
    </header>
    <jsp:include page="${_____CONTROLLER_VIEW_NAME_____}"/>    <footer>
        <jsp:include page="footer.jsp"/>
    </footer>
</body>
</html>

Spring MVC with ControllerClassNameHandlerMapping

Project Structure: (Download example)


springapp-servlet.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        <property name="caseSensitive" value="true" />
        <!--<property name="pathPrefix" value="/pathPrefix" />-->
    </bean>
    <bean class="com.pkm.controllers.UserController"/>    
    <bean id="viewResolver"
     class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
            <!--All controller based view file goes here-->
        </property>
        <property name="suffix">
            <value>.jsp</value>
            <!--View file extension would be jsp-->
        </property>
    </bean>
</beans>

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>springapp</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springapp</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

UserController.java


package com.pkm.controllers;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView; 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 
import java.io.IOException;
 
public class UserController implements Controller { 
    protected final Log logger = LogFactory.getLog(getClass()); 
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException { 
        logger.info("Returning hello view"); 
        logger.info(request.getQueryString());
        logger.info(request.getParameterMap());
        logger.info(request.getRequestURI());
        logger.info(request.getRequestURL());
        logger.info(request.getDispatcherType());
        ModelAndView modelAndView = new ModelAndView("user");
        modelAndView.addObject("obj1", "Object 1");
        modelAndView.addObject("obj2", "Object 2");
        return modelAndView;
    } 
}

WEB-INF/index.jsp


<html>
  <head><title>Example :: Spring Application</title></head>
  <body>
    <h1>Example - Spring Application</h1>
    <p>This is my test.</p>
    <a href="user.htm">GO TO USER CONTROLLER</a>
  </body>
</html>

WEB-INF/jsp/user.jsp


<html>
  <head><title>Hello :: Spring Application</title></head>
  <body>
    <h1>Hello - Spring Application</h1>
    <p>Greetings.</p>
    <p>Object1: ${obj1}</p>
    <p>Object2: ${obj2}</p>
  </body>
</html>

Sunday, August 31, 2014

Python: Generate XML From Dictionary Or List


import sys
import tempfile
from XmlToDict import XmlParser

class DictToXml():
    def __init__(self, dic):
        self.dic = dic;
        self.str = "";
        self.NEW_LINE = "\n";
        self.attr = '<<attr>>';
        self.value = '<<value>>';

    def toXml(self):
        self.rx(self.dic);
        return self.str;

    def rx(self, o):
        w = 'rootTag'
        c = 1;
        self.str += "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + self.NEW_LINE;
        if type(o) == type([]):
            self.rxl(o, w, c);
        else:
            self.rxd(o, w, c);

    def rxd(self, o, w, c):
        self.str += self.tb(c - 1) + "<" + w;
        for k, o2 in o.iteritems():
            if k == self.attr:
                for k2, v2 in o2.iteritems():
                    self.str += " " + k2 + "=\"" + v2 + "\"";        
        ot = 0
        self.str += ">" + self.NEW_LINE;
        for k, o2 in o.iteritems():
            if k == self.attr:
                pass
            elif type(o2) == type ([]):
                self.rxl(o2, k, c + 1);
                ot = ot + 1;
            elif k == self.value:
                self.str = self.str[:-1]
                self.str += str(o2);
            elif type(o2) == type ({}):
                self.rxd(o2, k, c + 1);
                ot = ot + 1;
            else:                
                self.str += self.tb(c) + "<" + k + ">";
                self.str += str(o2);
                self.str += "</" + k + ">" + str(self.NEW_LINE);
                ot = ot + 1
        if ot == 0:
            self.str += self.tb(0) + "</" + w + ">" + str(self.NEW_LINE);
        else:
            self.str += self.tb(c - 1) + "</" + w + ">" + str(self.NEW_LINE);

    def rxl(self, o, w, c):
        for o2 in o:
            if type(o2) == type ({}):
                self.rxd(o2, w, c);
                #self.str += self.NEW_LINE;
            elif type(o2) == type ([]):
                self.str += self.tb(c - 1) + "<" + w + ">" + self.NEW_LINE;
                self.rxl(o2, w, c + 1);
                self.str += self.tb(c - 1) + "</" + w + ">" + self.NEW_LINE;
            else:
                self.str += self.tb(c - 1) + "<" + w + ">";
                self.str += str(o2);
                self.str += "</" + w + ">" + self.NEW_LINE;

    def tb(self, c):
        st = "";
        for num in range (0, c):
            st += str("    ");
        return st;
        
        
        
if __name__ == "__main__":
    dicobj = {}
    listobj = []
    list2 = []
    for num in range(1, 3):
        dicobj['key' + str(num)] = {};
        dicobj['key' + str(num)]['otherkey'] = str(num)
        dicobj['key' + str(num)]['<<attr>>'] = {}
        dicobj['key' + str(num)]['<<attr>>']['att1'] = 'att1: ' + str(num);
        dicobj['key' + str(num)]['<<attr>>']['att2'] = 'att2: ' + str(num);
        listobj.append(num)
        list2.append("LIST: " + str(num));
    for num in range(4, 6):
        dicobj['key' + str(num)] = {};
        dicobj['key' + str(num)]['<<value>>'] = str(num)
        dicobj['key' + str(num)]['<<attr>>'] = {}
        dicobj['key' + str(num)]['<<attr>>']['att1'] = 'att1: ' + str(num);
        dicobj['key' + str(num)]['<<attr>>']['att2'] = 'att2: ' + str(num);
        listobj.append(num)
        list2.append("LIST: " + str(num));
    listobj.append(list2)
    listobj.append({'nl': 'hmm', 'tl': 'just tl', '<<attr>>': {'att1': 'Att1'}});
    dicobj['list'] = listobj
    #print dicobj
    txml = DictToXml(dicobj).toXml()
    # printing xml string generated from data dictionary
    print txml
    print ''
    # saving xml string to a temporary file
    f = tempfile.NamedTemporaryFile(delete=False)
    f.write(txml);
    f.seek(0);
    f.close();

    # parsing the xml file using my XmlParser
    xmlObj = XmlParser(f.name);
    theXmlDictionary = xmlObj.parse()
    # priting the data dictionary as pretty format generated from xml
    xmlObj.printDic(theXmlDictionary);

    # again generating xml from data dictionary...
    print DictToXml(theXmlDictionary['rootTag']).toXml()

Output would be like this:


<?xml version="1.0" encoding="UTF-8" ?>
<rootTag>
    <key2 att2="att2: 2" att1="att1: 2">
        <otherkey>2</otherkey>
    </key2>
    <key1 att2="att2: 1" att1="att1: 1">
        <otherkey>1</otherkey>
    </key1>
    <list>1</list>
    <list>2</list>
    <list>4</list>
    <list>5</list>
    <list>
        <list>LIST: 1</list>
        <list>LIST: 2</list>
        <list>LIST: 4</list>
        <list>LIST: 5</list>
    </list>
    <list att1="Att1">
        <tl>just tl</tl>
        <nl>hmm</nl>
    </list>
    <key5 att2="att2: 5" att1="att1: 5">5</key5>
    <key4 att2="att2: 4" att1="att1: 4">4</key4>
</rootTag>


rootTag: {
   key2: {
      <<attr>>: {
         att2 :  att2: 2
         att1 :  att1: 2
      }
      otherkey :  2
   }
   key1: {
      <<attr>>: {
         att2 :  att2: 1
         att1 :  att1: 1
      }
      otherkey :  1
   }
   list: [
      0. 1
      1. 2
      2. 4
      3. 5
      4. {
         list: [
            0. LIST: 1
            1. LIST: 2
            2. LIST: 4
            3. LIST: 5
         ]
      }
      5. {
         <<attr>>: {
            att1 :  Att1
         }
         tl :  just tl
         nl :  hmm
      }
   ]
   key5: {
      <<attr>>: {
         att2 :  att2: 5
         att1 :  att1: 5
      }
      <<value>> :  5
   }
   key4: {
      <<attr>>: {
         att2 :  att2: 4
         att1 :  att1: 4
      }
      <<value>> :  4
   }
}
<?xml version="1.0" encoding="UTF-8" ?>
<rootTag>
    <key2 att2="att2: 2" att1="att1: 2">
        <otherkey>2</otherkey>
    </key2>
    <key1 att2="att2: 1" att1="att1: 1">
        <otherkey>1</otherkey>
    </key1>
    <list>1</list>
    <list>2</list>
    <list>4</list>
    <list>5</list>
    <list>
        <list>LIST: 1</list>
        <list>LIST: 2</list>
        <list>LIST: 4</list>
        <list>LIST: 5</list>
    </list>
    <list att1="Att1">
        <tl>just tl</tl>
        <nl>hmm</nl>
    </list>
    <key5 att2="att2: 5" att1="att1: 5">5</key5>
    <key4 att2="att2: 4" att1="att1: 4">4</key4>
</rootTag>