Showing posts with label spring. Show all posts
Showing posts with label spring. 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

Saturday, October 11, 2014

HANDLING CUSTOM ERROR PAGES IN TOMCAT WITH SPRING MVC

Download full source code from here
web.xml
<error-page>
    <location>/error.jsp</location>
</error-page>
Create a file named 'error.jsp' under 'WEB-INF' with following contents. This jsp file will redirect to error404 action under error controller.
<!DOCTYPE html>
<%@taglib prefix="UiTabLib" uri="UiTabLib" %>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="REFRESH" content="0;url=<UiTabLib:contextPath/>error/error404.htm?<UiTabLib:logError 

request="${requestScope}"/>">
    </head>
    <body>
        &nbsp;
    </body>
</html>
ErrorController.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 ErrorController extends MultiActionController {
    public ModelAndView error404(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
        String statusCode = request.getParameter("status_code");
        String exception = request.getParameter("exception");
        String requestUri = request.getParameter("request_uri");
        if (requestUri == null) {
            requestUri = "Unknown";
        }
  
        ModelAndView view = new ModelAndView("error/error404");
        view.addObject("statusCode", statusCode);
        view.addObject("exception", exception);
        view.addObject("requestUri", requestUri);
        
        return view; 
    }
}
Create a file named 'error404.jsp' under 'WEB-INF/jsp/error/' folder with following content:
<div>Request URI: ${requestUri}</div>
<div>Status Code: ${statusCode}</div>
<div>Exception: ${exception}</div>


Friday, September 19, 2014

Spring MVC - Custom Exception Handling & Send Appropriate Error Code

Download full source code


Create a custom exception handler class as follows:


package com.pkm.maven.exception;

public class SpringException extends RuntimeException {
    private String exceptionMsg;
    
    public SpringException(String exceptionMsg) {
        this.exceptionMsg = exceptionMsg;
    }
    
    public String getExceptionMsg() {
        return this.exceptionMsg;
    }
    
    public void setExceptionMsg(String exceptionMsg) {
        this.exceptionMsg = exceptionMsg;
    }
}

Add following lines of code to your XXX-servlet.xml under WEB-INF


<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <prop key="com.pkm.maven.exception.SpringException">ExceptionPage</prop>
        </props>
    </property>
    <property name="defaultErrorView" value="error"/>
</bean>

Create a jsp page named 'ExceptionPage.jsp' defined in previous XXX-servlet.xml file under WEB-INF folder.


<h3 class="error">${exception.exceptionMsg}</h3>

Also create a file named 'error.jsp' under WEB-INF/jsp/ folder


<h3>General Error Page</h3>

Now time to throw custom exception

From method1 & method2 i am throwing my custom error so rendering my custom error page 'ErrorPage.jsp' & in method4, I am not throwing any exception but when invoking the line 'nullString.length()', it automatically throwing general exception, so rendering 'error.jsp' as defined in XXX-servlet.xml.


package com.pkm.maven.controller;

import com.pkm.maven.exception.SpringException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

/**
 * Controller action would be like this
 * public (ModelAndView | Map | String | void) actionName(HttpServletRequest, HttpServletResponse [,HttpSession] [,CommandObject]);
 * @author Pritom K Mondal
 */

public class CustomerController extends MultiActionController {    
    public ModelAndView method1(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
        throw new SpringException("Error from customer controller and method1() action.");
        //return new ModelAndView("CustomerPage", "msg", "method1() method"); 
    }
 
    public ModelAndView method2(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        response.setStatus( HttpServletResponse.SC_BAD_REQUEST  );
        throw new Exception("Error from customer controller and method2() action.");
        //return new ModelAndView("CustomerPage", "msg", "method2() method"); 
    }
 
    public ModelAndView method3(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        return new ModelAndView("CustomerPage", "msg", "method3() method"); 
    }
 
    public ModelAndView method4(HttpServletRequest request, HttpServletResponse response) throws Exception { 
        String nullString = null;
        Integer length = nullString.length();
        return new ModelAndView("CustomerPage", "msg", "method4() method"); 
    }
}

Output would be like this in browser if you browse 'customer/method1' or 'customer/method2':


Output would be like this in browser if you browse 'customer/method4':


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