Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Spring Exception Handling Example

Spring Exception Handling Example

The following example show how to write a simple web based application using Spring MVC Framwork, which can handle one or more exceptions raised inside its controllers. To start with it, let us have working Eclipse IDE in place and follow the following steps to develope a Dynamic Form based Web Application using Spring Web Framework:

Step 1: Create a Dynamic Web Project with a name SpringException and create following 3 new folder under src folder in the created project
1. Controller
2. Service
3. Dao

Step 2: Copy Spring and other project specific libraries into the folder WebContent/WEB-INF/lib

Step 3 : Now create below packages in specific folder 
1. In Controller folder create package : com.gea.controller  
2. In Service folder create package : com.gea.services  
3. In Dao folder create package : com.gea.dao  

Step 4:  Create Spring configuration files Web.xml and spring-servlet.xml under the WebContent/WEB-INF folder.
 
Step 5: Create a sub-folder with a name jsp under the WebContent/WEB-INF folder. Create a view files 404error.jsp,errro.jsp,ExceptionPage.jsp,index.jsp,viewForm.jsp.

Step 6: Now Follow below steps and run program in your browser.

WelcomeController.java


SpringException.java
WelcomeServices.java

posted under , | 0 Comments

Spring MVC Fast Tutorial: Hello World

How Spring MVC works

Basically the same way as Struts: 

 

  •  Based on the HTTP request URL, the DispatcherServlet calls the corresponding Controller.
  • A View is rendered and sent as HTTP response.

Spring Servlet Declaration

In 'WEB-INF/web.xml', we declare Spring DispatcherServlet and map '*.html' URLs to it:

 
  
    springmvc
    org.springframework.web.servlet.DispatcherServlet
    1
  
 
  
    springmvc
    *.html
  
 
  
    
      jsp/index.jsp
    
  
 

Spring Servlet Configuration

Let's now create the Spring configuration file 'WEB-INF/springmvc-servlet.xml' (name based on the servlet name above):

 
  
 
  
      
      
      
  
 

Map URL /hello_world.html to Controller HelloWorldController Declare View Resolver: when view 'view_name' is called (from the Controller), the file '/jsp/view_name.jsp' will be used.

Controller

Let's create the Controller 'WEB-INF/src/springmvc/web/HelloWorldController.java':
package springmvc.web;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
 
public class HelloWorldController implements Controller {
 
 public ModelAndView handleRequest(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
 
  String aMessage = "Hello World MVC!";
 
  ModelAndView modelAndView = new ModelAndView("hello_world");
  modelAndView.addObject("message", aMessage);
 
  return modelAndView;
 }
}
This Controller calls the view 'hello_world', passing 'message' to it (like a Struts attribute).

View

Displays the message attribute previously set in the Controller.

Make it work

 

 

http://localhost:8180/springmvc/hello_world.html

  • We declared Spring servlet in web.xml 
  • We created a Spring configuration file where we mapped an URL to a controller and defined a way to resolve views. 
  • We created a controller and a view

posted under , | 0 Comments

How to make logging facility in project using AOP in spring

Logging Facility using AOP Spring

 
package com.gea.utility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect
{
    private Log log = LogFactory.getLog(this.getClass());
    
    //@Pointcut("execution(* *.*(..))")
    @Pointcut("execution(* com.gea..*.*(..))")
    protected void loggingOperation() {}
    
    @Before("loggingOperation()")
    @Order(1)
    public void logJoinPoint(JoinPoint joinPoint)
    {
      log.info("Join point kind : " + joinPoint.getKind());
     log.info("Signature declaring type : "+ joinPoint.getSignature().getDeclaringTypeName());
  log.info("Signature name : " + joinPoint.getSignature().getName());
        log.info("Arguments : " + Arrays.toString(joinPoint.getArgs()));
        log.info("Target class : "+ joinPoint.getTarget().getClass().getName());
        log.info("This class : " + joinPoint.getThis().getClass().getName());
     
     StringBuilder sb = new StringBuilder(joinPoint.getSignature().getDeclaringTypeName());
     sb.append(" -->");
     sb.append(joinPoint.getSignature().getName()+"() Method Start");
     log.info(sb.toString());
    }
        
    @AfterReturning(pointcut="loggingOperation()", returning = "result")
    @Order(2)
    public void logAfter(JoinPoint joinPoint, Object result)
    {
     log.info("Exiting from Method :"+joinPoint.getSignature().getName());
     log.info("Return value :"+result);

     StringBuilder sbLogAfter = new StringBuilder(joinPoint.getSignature().getDeclaringTypeName());
     sbLogAfter.append(" -->");
     sbLogAfter.append(joinPoint.getSignature().getName()+"() Method End");
     log.info(sbLogAfter.toString());
    }
    
    @AfterThrowing(pointcut="execution(* com.gea..*.*(..))", throwing = "e")
   // @AfterThrowing(pointcut="execution(* *.*(..))", throwing = "e")
    @Order(3)
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e)
    {
     log.error("An exception has been thrown in "+ joinPoint.getSignature().getName() + "()");
        log.error("Cause :"+e.getCause());
        
        StringBuilder sbLogAfter = new StringBuilder("An exception has been thrown in "+joinPoint.getSignature().getDeclaringTypeName());
     sbLogAfter.append(" -->");
     sbLogAfter.append(joinPoint.getSignature().getName()+"() Method End");
     log.error(sbLogAfter.toString());
    }
    
//    @Around("execution(* *.*(..))")
    @Around("execution(* com.gea..*.*(..))")
    @Order(4)
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable
    {
  log.info("The method " + joinPoint.getSignature().getName()+ "() begins with " + Arrays.toString(joinPoint.getArgs()));
        try
        {
            Object result = joinPoint.proceed();
            log.info("The method " + joinPoint.getSignature().getName()+ "() ends with " + result);
            return result;
        } catch (Throwable e)
        {
            log.error("Illegal argument "+ Arrays.toString(joinPoint.getArgs()) + " in "+ joinPoint.getSignature().getName() + "()");
            throw e;
        }        
    }
    
}


Note : Above code is usefull for spring annotation based project, We are required only one class to activate logging facility in our system. No need to define logger for all method in our code , when we entered into method and goes out from the method.

Following changes would required to implement logging facility in spring project.

File Name : spring-servlet.xml
   
   
   
   

Following two library must be avaiable in your class path with it's dependant library.
  1. spring-aop-3.2.3.RELEASE.jar
  2. spring-aspects-3.2.3.RELEASE.jar
How it's work ? 








 

Older Posts Home

Followers

Powered by Blogger.

Populares

Custom Search