Showing posts with label spring framework. Show all posts
Showing posts with label spring framework. Show all posts

Friday, November 14, 2014

Spring MVC custom body tag library example


Create two java file with following contents:

package com.pkm.maven.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class BodyTagOne extends BodyTagSupport {
    private int mTimes = 0;
    private BodyContent mBodyContent;
    
    public void setTimes(int pTimes) {
        mTimes = pTimes;
    }
    
    @Override
    public void setBodyContent(BodyContent pBodyContent) {
        mBodyContent = pBodyContent;
    }
    
    @Override
    public int doStartTag() throws JspException {
        if (mTimes >= 1) {
            return EVAL_BODY_TAG;
        } else {
            return SKIP_BODY;
        }
    }
    
    @Override
    public int doAfterBody() throws JspException {
        if (mTimes > 1) {
            mTimes--;
            return EVAL_BODY_TAG;
        } else {
            return SKIP_BODY;
        }
    }

    
    @Override
    public int doEndTag() throws JspException {
        try {
            if (mBodyContent != null) {
                mBodyContent.writeOut(mBodyContent.getEnclosingWriter());
            }
        } catch (Exception pIOEx) {
            throw new JspException("Error: " + pIOEx.getMessage());
        }
        return EVAL_PAGE;
    }
}





package com.pkm.maven.tag;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class BodyTagTwo extends BodyTagSupport {    
    @Override
    public int doAfterBody() throws JspException {
        try {
            BodyContent bc = getBodyContent();
            String body = bc.getString();
            JspWriter out = bc.getEnclosingWriter();
            if (body != null) {
                body = body.substring(0, 1).toUpperCase() + body.substring(1);
                out.print(body);
            }
        } 
        catch (Exception ioe) {
            throw new JspException("Error: " + ioe.getMessage());
        }
        return SKIP_BODY;
    }
}

Create the tag library descriptor (TLD) under WEB-INF folder suppose named: "UiTabLib.tld":

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
         version="2.0">
 
     <tlib-version>1.0</tlib-version>
     <short-name>Ui Tab Library</short-name>
     <uri>UiTabLib</uri>
 
     <tag>
        <name>loopText</name>
        <tag-class>com.pkm.maven.tag.BodyTagOne</tag-class>
        <body-content>JSP</body-content>
        <info>This Tag Displayes given text multiple times</info>
        <attribute>
            <name>times</name>
            <required>true</required>
            <description>Provide number of times the text will be repeated</description>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
    </tag>
     <tag>
        <name>capitalize</name>
        <tag-class>com.pkm.maven.tag.BodyTagTwo</tag-class>
        <body-content>JSP</body-content>
        <info>This Tag Displays given string to be capitalized</info>
    </tag>
</taglib>

Reference & use the tag library:

<p>
    Body Tag Example: <br/>
    <% Integer counter = 1; %>
    <UiTabLib:loopText times="10">
        Counter: <%= (counter++) %><br/>
    </UiTabLib:loopText>
   <%= counter %>
</p>
<p>
    String capitalize (text to be capitalized): 
    <UiTabLib:capitalize>text to be capitalized</UiTabLib:capitalize>
</p>

Output would be like this:

Body Tag Example: 
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Counter: 6
Counter: 7
Counter: 8
Counter: 9
Counter: 10
11
String capitalize (text to be capitalized): Text to be capitalized

Spring MVC simple custom tag library example

Create a java file with following contents:

package com.pkm.maven.tag;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class NewDateTag extends SimpleTagSupport {
    private String prefix;
 
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    
    @Override
    public void doTag() throws JspException, IOException {
        final JspWriter writer = getJspContext().getOut();
        String pattern = "dd/MM/yyyy H:m:s";
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        if (prefix != null) {
            writer.print(prefix + " ");
        }
        writer.print(format.format(new Date()));
    }
}

Create the tag library descriptor (TLD) under WEB-INF folder suppose named: "UiTabLib.tld":

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
         version="2.0">
 
     <tlib-version>1.0</tlib-version>
     <short-name>Ui Tab Library</short-name>
     <uri>UiTabLib</uri>
  
     <tag>
         <name>newDate</name>
         <tag-class>com.pkm.maven.tag.NewDateTag</tag-class>
         <body-content>empty</body-content>
         <attribute>
             <name>prefix</name>
             <type>java.lang.String</type>
             <required>false</required>
             <rtexprvalue>true</rtexprvalue>
         </attribute>
     </tag>
</taglib>

Reference & use the tag library:

<%@taglib prefix="UiTabLib" uri="UiTabLib" %>

<p>New Date Tag Lib Output: <UiTabLib:newDate/></p>
<p>New Date Tag Lib Output: <UiTabLib:newDate prefix="Prefix"/></p>

Output would be like this:

New Date Tag Lib Output: 14/11/2014 18:25:12
New Date Tag Lib Output: Prefix 14/11/2014 18:25:12

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 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>

Tuesday, January 14, 2014

Setup Spring framework with Eclipse IDE and create first application


Step 1: Setup Java Development Kit (JDK)

Download the latest version of SDK from Oracle's Java site: Java SE Downloads. Install SDK as instruction from oracle site. After installation completed, set PATH and JAVA_HOME environment variables.
If you are running Windows and installed the JDK in "C:\Program Files\Java\jdk1.6.0_24", you would have to put the following line in your C:\autoexec.bat file.
set PATH=C:\Program Files\Java\jdk1.6.0_24\bin;%PATH%
set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_24
Alternatively, on Windows XP, right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_24 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.6.0_24/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1.6.0_24
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as given document of the IDE.

Step 2: Install Apache Common Logging API

Download the latest version of Apache Commons Logging API from here (version: 1.1.3) or from http://commons.apache.org/logging/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\commons-logging-1.1.3 on windows, or /usr/local/commons-logging-1.1.3 on Linux/Unix. This directory will have following jar files and other supporting documents etc.



Step 3: Setup Eclipse IDE

Download the latest Eclipse from http://www.eclipse.org/downloads/ and unpack the binary distribution into a folder for example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.
Eclipse can be started by executing the following commands on windows machine, or you can simply double click on eclipse.exe
 %C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$/usr/local/eclipse/eclipse

Step 4: Setup Spring Framework Libraries

  1. Make a choice whether you want to install Spring on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix.
  2. Download the latest version of Spring framework binaries from http://repo.spring.io/release/org/springframework/spring/ or version 3.2.0 from here.
  3. Unzip the downloaded file, as for me, the extracted folder is 'D:\me\Apache Loggin Jars\spring-framework-3.2.0.RELEASE\libs'.


Step 5: Create Java Project

The first step is to create a simple Java Project using Eclipse IDE. Follow the option File -> New -> Project and finally select Java Project wizard from the wizard list. Now name your project as 'First Spring' using the wizard window as follows:





Step 6: Add Required Libraries

As a second step let us add Spring Framework and common logging API libraries in our project. To do this, right click on your project name FirstSpring and then follow the following option available in context menu: Build Path -> Configure Build Path to display the Java Build Path window as follows:
Now use Add External JARs button available under Libraries tab to add the following core JARs from Spring Framework and Common Logging installation directories



Step 7: Create Source Files

Now let us create actual source files under the FirstSpring project. First we need to create a package called com.pritom.code. To do this, right click on src in package explorer section and follow the option : New -> Package.
Next we will create FirstSpring.java and MainApplication.java files under the 'com.pritom.code'.


Here is the content of FirstSpring.java file:


package com.pritom.code;

public class FirstSpring {
	private String message;

	public void setMessage(String message){
		this.message  = message;
	}

	public void getMessage(){
		System.out.println("I am writting from mainApplication: " + message);
	}
}


Following is the content of the second file MainApplication.java:


package com.pritom.code;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApplication {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

		FirstSpring obj = (FirstSpring) context.getBean("firstSpring");

		obj.getMessage();
		
		obj.setMessage("New Message");
		obj.getMessage();
	}
}



Step 8: Create Bean Configuration File:

You need to create a Bean Configuration file which is an XML file named 'Beans.xml' and acts as cement that glues the beans ie. classes together. This file needs to be created under the src directory as shown below: 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="firstSpring" class="com.pritom.code.FirstSpring">
       <property name="message" value="First Spring!"/>
   </bean>

</beans>


Step 9: Running the Program:

Once you are done with creating source and beans configuration files, you are ready for this step which is compiling and running your program. To do this, Keep MainApplication.Java file tab active and use either Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your MainApplication application. If everything is fine with your application, this will print the following message in Eclipse IDE's console:
I am writting from mainApplication: First Spring!
I am writting from mainApplication: New Message 

Congratulations, you have created your first Spring Application successfully. You can see the flexibility of above Spring application by changing the value of "message" property and keeping both the source files unchanged