Monday 8 April 2013

Call Stored Procedures in Spring

6 comments
There are multiple ways to call stored procedure in Spring Framework
1. query() method from JdbcTemplate to call stored procedures
2. extend abstract class StoredProcedure to call stored procedures

Step 1: Create a store Procedure

mysql> DELIMITER // 
mysql> create procedure usp_GetEmployeeName(IN id INT, OUT name VARCHAR(20)) 
-> begin 
-> select emp_name into name from employee where emp_id = id; 
-> end//

 Query OK, 0 rows affected (0.52 sec) 
 
 
 mysql> DELIMITER ;


Step2: Java Class which wraps Stored procedure
 In this example, we have extended abstract class StoredProcedure in our class called, EmployeeSP. This is declared as nested class inside EmployeeDAO because its only used by this class, if your stored procedure is used my multiple DAO classes, than you can also make it a top level class. If you look at constructor of EmployeeSP, it calls super class constructor and passes datasource and name of database stored procedure. We have also declared two stored procedure parameters, one is IN parameter id, and other is OUT parameter. Input to stored procedure is passed using IN parameter, and output from stored procedure is read using OUT parameter. Your stored procedure can have multiple IN and OUT parameter. StoredProcedure class also provide several execute() methods, which can be invoked to call stored procedure and get result. It return result as Map, where key is OUT parameter, and value is result of stored procedure.

import java.sql.Types; 
import java.util.Map; 
import javax.sql.DataSource; 
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter; 
import org.springframework.jdbc.core.SqlParameter; 
import org.springframework.jdbc.object.StoredProcedure;
public class EmployeeDao 
{ 
 private JdbcTemplate jdbcTemplate;
 private EmployeeSP sproc; 
 public void setDataSource(DataSource source)
 { 
  this.jdbcTemplate = new JdbcTemplate(source); 
  this.sproc = new EmployeeSP(jdbcTemplate.getDataSource()); 
  } 
 
 /* * wraps stored procedure call */ 
 public String getEmployeeName(int emp_id)
 { 
  return (String) sproc.execute(emp_id); 
 } 
 
 /* * Inner class to implement stored procedure in spring. */ 
 private class EmployeeSP extends StoredProcedure
 { 
  private static final String SPROC_NAME = "usp_GetEmployeeName"; 
  public EmployeeSP( DataSource datasource )
  { 
   super( datasource, SPROC_NAME ); 
   declareParameter( new SqlParameter( "id", Types.INTEGER) ); //declaring sql in parameter to pass input 
   declareParameter( new SqlOutParameter( "name", Types.VARCHAR ) ); //declaring sql out parameter 
   compile(); 
  } 
  
  public Object execute(int emp_id)
  { 
   Map results = super.execute(emp_id); 
   return results.get("name"); //reading output of stored procedure using out parameters 
   } 
  } 
 }
   }
  }
}


Step3: Test stored procedure

import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
/* * Main class to start and test this Java application */ 
public class Main 
{ 
 public static void main(String args[])
 { 
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml"); 
  EmployeeDao dao = (EmployeeDao) ctx.getBean("employeeDao"); //calling stored procedure using DAO method 
  System.out.println("Employee name for id 103 is : " + dao.getEmployeeName(103)); } } 
 }
}


Output:
2013-01-17 23:56:34,408 0 [main] DEBUG EmployeeDao$EmployeeSP - Compiled stored procedure. Call string is [{call usp_GetEmployeeName(?, ?)}] 
2013-01-17 23:56:34,439 31 [main] DEBUG EmployeeDao$EmployeeSP - RdbmsOperation with SQL [usp_GetEmployeeName] compiled 
Employee name for id 103 is : Jack


spring-config.xml


        
                
                        
                                classpath:jdbc.properties
                        
                
        

    
        
        
        
        
    
      
        
                
        


Wednesday 3 April 2013

Rest Template Json Request

1 comments
On the server side
The controller:
@RequestMapping( value="/user/save", method=RequestMethod.POST, consumes="application/json" )
public @ResponseBody User saveUser( @RequestBody User user ) {
  
    userService.saveUser( user );
  
    return user;

}
servlet-context.xml:



 
 
 
 

             
 
 
 
 

 
 
 
 
 
     
     
 
 
 
 
         
                 
                     
                
        
 

 
 
        
 
 
On the client side The test:
package com.rest.client.test;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;



@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( "classpath:META-INF/conf/test-conf.xml" )
public class RestWebServiceTest {

    @Autowired
    private RestTemplate restTemplate;
 
 
    @Test
    public void shouldSaveJsonStringUser() {

        String jsonStringUser = "{"
        + "\"id\":\"\"" + ","
        + "\"firstName\":\"nicolas\"" + ","
        + "\"lastName\":\"loriente\""
        + "}";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType( MediaType.APPLICATION_JSON );

        HttpEntity request= new HttpEntity( jsonStringUser, headers );
  
        User returnedUser = restTemplate.postForObject( "http://localhost:8080/Rest/user/save", request, User.class );
  
        // user id is populated when saved to DB
        assertNotNull( returnedUser.getId() );
        assertEquals( "nicolas", returnedUser.getFirstName() );
        assertEquals( "loriente", returnedUser.getLastName() );

    }
 
    @Test
    public void shouldSaveObjectUser() {

        User user = new User();
        user.setFirstName( "nicolas" );
        user.setLastName( "loriente" );

        User returnedUser = restTemplate.postForObject( "http://localhost:8080/Rest/user/save", user, User.class );
  
        // user id is populated when saved to DB
        assertNotNull( returnedUser.getId() );
        assertEquals( "nicolas", returnedUser.getFirstName() );
        assertEquals( "loriente", returnedUser.getLastName() );

    }
 
}
test-conf.xml: Code:


 
 
 
  
 
 
         
                 
                     
                
        
 
 

Monday 1 April 2013

Autowire a Bean Spring

0 comments
SpringBeans.xml


 
 
 
  
  
 
  
 
  
 
 
Customer.java
package com;

import org.springframework.beans.factory.annotation.Autowired;

public class Customer {

 @Autowired
 private Person person;
 private int type;
 private String action;

 public Person getPerson() {
  return person;
 }

 public void setPerson(Person person) {
  this.person = person;
 }

 public int getType() {
  return type;
 }

 public void setType(int type) {
  this.type = type;
 }

 public String getAction() {
  return action;
 }

 public void setAction(String action) {
  this.action = action;
 }

 @Override
 public String toString() {
  return "Customer [person=" + person + ", type=" + type + ", action="
    + action + "]";
 }

 
}
Person.java
package com;

public class Person {
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @Override
 public String toString() {
  return "Person [name=" + name + "]";
 }

 
}
App.java
package com;

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

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

  Customer cust = (Customer) context.getBean("customer");
  Person per = (Person) context.getBean("person");
  
  System.out.println(cust);
  System.out.println(per);
 }
}
Output: 
Customer [person=Person [name=harit], type=1, action=buy]
Person [name=harit]

Auto-Wiring Beans Spring

0 comments

In Spring, 5 Auto-wiring modes are supported

no – Default, no auto wiring, set it manually via “ref” attribute
byName – Auto wiring by property name. If the name of a bean is same as the name of other bean property, auto wire it.
byType – Auto wiring by property data type. If data type of a bean is compatible with the data type of other bean property, auto wire it.
constructor – byType mode in constructor argument.
autodetect – If a default constructor is found, use “autowired by constructor”; Otherwise, use “autowire by type”.
Customer and Person Bean Classes
public class Customer 
{
 private Person person;
 
 public Customer(Person person) {
  this.person = person;
 }
 
 public void setPerson(Person person) {
  this.person = person;
 }
 //...
}
public class Person 
{
 //...
}
1. Auto-Wiring ‘no’ 
This is the default mode, you need to wire your bean via ‘ref’ attribute.

                  
 
 
 
2. Auto-Wiring ‘byName’ 
Auto-wire a bean by property name. In this case, since the name of “person” bean is same with the name of the “customer” bean’s property (“person”), so, Spring will auto wired it via setter method – “setPerson(Person person)“.

 
 
3. Auto-Wiring ‘byType’
 Auto-wire a bean by property data type. In this case, since the data type of “person” bean is same as the data type of the “customer” bean’s property (Person object), so, Spring will auto wired it via setter method – “setPerson(Person person)“
 
 
 
4. Auto-Wiring ‘constructor’ 
Auto-wire a bean by property data type in constructor argument. In this case, since the data type of “person” bean is same as the constructor argument data type in “customer” bean’s property (Person object), so, Spring auto wired it via constructor method – “public Customer(Person person)“.

 
 
5. Auto-Wiring ‘autodetect’ 
If a default constructor is found, uses “constructor”; Otherwise, uses “byType”. In this case, since there is a default constructor in “Customer” class, so, Spring auto wired it via constructor method – “public Customer(Person person)“

 
 

@InitBinder - Custom Spring Validator to a Spring MVC Controller

0 comments

This technique should be used when you need to do ALL your controller’s validation yourself, and you can’t or don’t want to make use of the Hibernate’s reference implementation of a JSR 303 validator. From this, you’ll guess that you can’t mix your own custom Spring validator with Hibernate’s JSR 303 validator.


The MVC command object is a simple matter of tying together a few address fields:

public class Address {

  private String street;

  private String town;

  private String country;

  private String postCode;

  public String getStreet() {

    return street;
  }

  public void setStreet(String street) {

    this.street = street;
  }

  public String getTown() {

    return town;
  }

  public void setTown(String town) {

    this.town = town;
  }

  public String getCountry() {

    return country;
  }

  public void setCountry(String country) {

    this.country = country;
  }

  public String getPostCode() {

    return postCode;
  }

  public void setPostCode(String post_code) {

    this.postCode = post_code;
  }
}

Create a custom validator

@Component
public class AddressValidator implements Validator {

  /**
   * Return true if this object can validate objects of the given class. This is cargo-cult
   * code: all implementations are the same and can be cut 'n' pasted from earlier examples.
   */
  @Override
  public boolean supports(Class clazz) {

    return clazz.isAssignableFrom(Address.class);
  }

  /**
   * Validate an object, which must be a class type for which the supports() method returned
   * true.
   *
   * @param obj The target object to validate
   * @param errors contextual state info about the validation process (never null)
   */
  @Override
  public void validate(Object obj, Errors errors) {

    Address address = (Address) obj;
    String postCode = address.getPostCode();
    validatePostCode(postCode, errors);
  }

  private void validatePostCode(String postCode, Errors errors) {

    if (isValidString(postCode) && isNotBirminghamPostCode(postCode)) {
      errors.rejectValue("postCode", "AddressValidator.postCode.notBirmingham",
          "Not a Birmingham Post Code");
    }
  }

  private boolean isValidString(String str) {

    return isNotNull(str) && (str.length() > 0);
  }

  private boolean isNotNull(String postCode) {

    return postCode != null;
  }

  /** The first character of the Birmingham post code is 'B' */
  private boolean isNotBirminghamPostCode(String postCode) {

    char val = postCode.charAt(0);
    return val != 'B';
  }
}

Attaching the validator to the controller is pretty straight forward. The first step is to annotate the Address command object with @Valid:

 @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addAddress(@Valid Address address, BindingResult result, Model model) {




The second step is to inject the validator into the data binder:

@InitBinder
  protected void initBinder(WebDataBinder binder) {

    binder.setValidator(addressValidator);
  }

Adding these two code snippets together, the complete AddressController code looks like this:

@Controller
public class AddressController {

  private static final String FORM_VIEW = "address.page";

  private static final String PATH = "/address";

  @Autowired
  private AddressValidator addressValidator;

  /**
   * Create the initial blank form
   */
  @RequestMapping(value = PATH, method = RequestMethod.GET)
  public String getCreateForm(Model model) {

    model.addAttribute(new Address());
    return FORM_VIEW;
  }

  /**
   * Attach the custom validator to the Spring context
   */
  @InitBinder
  protected void initBinder(WebDataBinder binder) {

    binder.setValidator(addressValidator);
  }

  /**
   * This is the handler method. Check for errors and proceed to the next view
   */
  @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addAddress(@Valid Address address, BindingResult result, Model model) {

    if (!result.hasErrors()) {
      model.addAttribute("noErrors",
          "No Errors This Time for postal code: " + address.getPostCode());
    }

    return FORM_VIEW;
  }
}

Same Validation Using JSR 303 validator

public class Address {

  // These JSR 303 built in annotations don't do anything
  // When you've injected your own validator
  @NotEmpty
  @Size(min = 1, max = 12)
  private String street;

  @NotEmpty
  private String town;

  @NotEmpty
  private String country;

  @NotEmpty
  private String postCode;

Spring MVC’s @ModelAttribute Annotation

0 comments
The @ModelAttribute annotation is used as part of a Spring MVC web app and can be used in two scenarios.

  • Firstly, it can be used to inject data objects the model before a JSP loads. This makes it particularly useful in ensuring that a JSP has all the data is needs to display itself. The injection is achieved by binding a method return value to the model.
  • Secondly, it can be used to read data from an existing model assigning it to handler method parameters.

To demonstrate the @ModelAttributes, I'm using the simplest of scenarios: adding a user account to a hypothetical system and then, once the user account has been created, displaying the new user’s details on a welcome screen.

In order to start the ball rolling, I’ll need a simple User bean with some familiar fields: first name, last name, nick name and email address - the usual suspects.
public class User {

  private String firstName;

  private String lastName;

  private String nickName;

  private String emailAddress;

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getNickName() {
    return nickName;
  }

  public void setNickName(String nickName) {
    this.nickName = nickName;
  }

  public String getEmailAddress() {
    return emailAddress;
  }

  public void setEmailAddress(String emailAddress) {
    this.emailAddress = emailAddress;
  }
}

I’ll also need a Spring MVC controller to handle creating users. This will contains a couple of important methods that use the @ModelAttribute annotation, demonstrating the functionality outlined above.
 The method below demonstrates how to bind a method return value to a model.
/**
   * This creates a new User object for the empty form and stuffs it into
   * the model
   */
  @ModelAttribute("User")
  public User populateUser() {
    User user = new User();
    user.setFirstName("your first name");
    user.setLastName("your last name");
    return user;
  }

This method is called before every @RequestMapping annotated handler method to add an initial object to the model, which is then pushed through to the JSP. Notice the word every in the above sentence. The @ModelAttribute annotated methods (and you can have more than one per controller) get called irrespective of whether or not the handler method or JSP uses the data. In this example, the second request handler method call doesn’t need the new user in the model and so the call is superfluous. Bare in mind that this could possibly degrade application performance by making unnecessary database calls etc. It’s therefore advisable to use this technique only when each handler call in your Controller class needs the same common information adding to the model for every page request. In this example, it would be more efficient to write:



 /**
   * Create the initial blank form
   */
  @RequestMapping(value = PATH, method = RequestMethod.GET)
  public String createForm() {

    populateUser();
    return FORM_VIEW;
  }
The method below demonstrates how to annotate a request method argument, so that data is extracted from the model and bound to the argument.
 /**
   * This is the handler method. Stick the user bean into a new attribute for
   * display on the next page
   *
   * @param user
   *            The user bean taken straight from the model
   * @param model
   *            An out param. Takes the user and adds it to the model FOR the
   *            NEXT page under a different name.
   *
   */
  @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addUser(@ModelAttribute("user") User user,
      BindingResult result, Model model) {

    model.addAttribute("newUser", user);
    return WELCOME_VIEW;
  }
In this example, an ‘add user’ button on a form has been pressed calling the addUser() method. The addUser() method needs a User object from the incoming model, so that the new user’s details can be added to the database. The @ModelAttribute("user") annotation applied takes any matching object from the model with the “user” annotation and plugs it into the User user method argument.

Just for the record, this is the full controller code.

@Controller
public class AddUserController {

  private static final String FORM_VIEW = "adduser.page";

  private static final String WELCOME_VIEW = "newuser.page";

  private static final String PATH = "/adduser";

  /**
   * Create the initial blank form
   */
  @RequestMapping(value = PATH, method = RequestMethod.GET)
  public String createForm() {

    return FORM_VIEW;
  }

  /**
   * This creates a new User object for the empty form and stuffs it into
   * the model
   */
  @ModelAttribute("User")
  public User populateUser() {
    User user = new User();
    user.setFirstName("your first name");
    user.setLastName("your last name");
    return user;
  }

  /**
   * This is the handler method. Stick the user bean into a new attribute for
   * display on the next page
   *
   * @param user
   *            The user bean taken straight from the model
   * @param model
   *            An out param. Takes the user and adds it to the model FOR the
   *            NEXT page under a different name.
   *
   */
  @RequestMapping(value = PATH, method = RequestMethod.POST)
  public String addUser(@ModelAttribute("user") User user,
      BindingResult result, Model model) {

    model.addAttribute("newUser", user);
    return WELCOME_VIEW;
  }
}

Exception Handling with the Spring 3.2 @ControllerAdvice Annotation

0 comments
As you seen in before post that the sample code contains a  controller with a request handler method that throws an IOException. The IOException is then handled by another method in the same controller that's annotated with @ExceptionHandler(IOException.class). The problem is that your method that's annotated with @ExceptionHandler(IOException.class) can only handle IOExceptions thrown by its containing controller. If you want to create a global exception handler that handles exceptions thrown by all controllers then you have to revert to something like Spring 2's SimpleMapingExceptionHandler and some XML configuration.

The controllers that generate the exceptions are fairly straightforward and listed below:
@Controller
public class UserCreditCardController {

  private static final Logger logger = LoggerFactory.getLogger(UserCreditCardController.class);

  /**
   * Whoops, throw an IOException
   */
  @RequestMapping(value = "userdetails", method = RequestMethod.GET)
  public String getCardDetails(Model model) throws IOException {

    logger.info("This will throw an IOException");

    boolean throwException = true;

    if (throwException) {
      throw new IOException("This is my IOException");
    }

    return "home";
  }

}
@Controller
public class UserAddressController {

  private static final Logger logger = LoggerFactory.getLogger(UserAddressController.class);

  /**
   * Whoops, throw an IOException
   */
  @RequestMapping(value = "useraddress", method = RequestMethod.GET)
  public String getUserAddress(Model model) throws IOException {

    logger.info("This will throw an IOException");

    boolean throwException = true;

    if (throwException) {
      throw new IOException("This is my IOException");
    }

    return "home";
  }

}
As you can see, all that this code does is to map userdetails and useraddress to the getCardDetails(...) and getUserAddress(...) methods respectively. When either of these methods throw an IOException, then the exception is caught by the following class:
@ControllerAdvice
public class MyControllerAdviceDemo {

  private static final Logger logger = LoggerFactory.getLogger(MyControllerAdviceDemo.class);

  @Autowired
  private UserDao userDao;

  /**
   * Catch IOException and redirect to a 'personal' page.
   */
  @ExceptionHandler(IOException.class)
  public ModelAndView handleIOException(IOException ex) {

    logger.info("handleIOException - Catching: " + ex.getClass().getSimpleName());
    return errorModelAndView(ex);
  }

  /**
   * Get the users details for the 'personal' page
   */
  private ModelAndView errorModelAndView(Exception ex) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("error");
    modelAndView.addObject("name", ex.getClass().getSimpleName());
    modelAndView.addObject("user", userDao.readUserName());

    return modelAndView;
  }
}

The class above is annotated by the new @ControllerAdvice annotation and contains a single public method handleIOException(IOException.class). This method catches all IOExceptions thrown by the controllers above, generates a model containing some relevant user information and then displays and error page. The nice thing about this is that,no matter how many controllers your application contains, when any of them throws an IOException, then it'll be handled by the MyControllerAdviceDemo exception handler.

@ModelAttribute and @InitBinder 
One final thing to remember is that the although the ControllerAdvice annotation is useful for handling exceptions, it can also be used the globally handle the @ModelAttribute and @InitBinder annotations. The combination of ControllerAdvice and @ModelAttribute gives you the facility to setup model objects for all controllers in one place and likewise the combination of ControllerAdvice and @InitBinder allows you to attach the same custom validator to all your controllers, again, in one place.

Spring 3 MVC Exception Handlers

0 comments
The controller code below is the first step in generating an error. The idea is that it’s supposed to return the user to our home page, but in the mists of processing the user’s request it throws a simple IOException. Once thrown, the exception is caught by this method:
 /**
   * Whoops, throw an IOException
   */
  @RequestMapping(value = "/ioexception", method = RequestMethod.GET)
  public String throwIoException(Locale locale, Model model) throws IOException {

    logger.info("This will throw an IOExceptiom");

    boolean throwException = true;

    if (throwException) {
      throw new IOException("This is my IOException");
    }

    return "home";
  }
/**
   * Catch IOException and redirect to a 'personal' page
   */
  @ExceptionHandler(IOException.class)
  public ModelAndView handleIOException(IOException ex) {

    logger.info("handleIOException - Catching: " + ex.getClass().getSimpleName());
    return errorModelAndView(ex);
  }

  /**
   * Get the users details for the 'personal' page
   */
  private ModelAndView errorModelAndView(Exception ex) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("error");
    modelAndView.addObject("name", ex.getClass().getSimpleName());
    modelAndView.addObject("user", userDao.readUserName());

    return modelAndView;
  }
To set this up is really simple, all you need to do is to add:

 @ExceptionHandler(IOException.class)

 to a method signature, et voila you’re done ...and that’s the simple bit over with. There are some points worth noting here: firstly, using

 @ExceptionHandler(IOException.class) 

 …will adhere to the usual contract for exception handling. This means that not only will the method above catch all IOExceptions, it’ll also catch all exceptions that are subclasses of IOException;

hence, if my throwAnException(..) method threw a FileNotFoundException it’ll still be caught by my handleIOException(...) method.

 Secondly, there is a very flexible, but ultimately limited, set of method signatures that you can use for exception handler methods. The full documentation for this is provided by Spring’s JavaDoc, but in summary you can devise a signature that contains any of the following input arguments in any order:

 Exception or one of its subclasses
 ServletRequest or HttpServletRequest
 ServletResponse or HttpServletResponse
 HttpSession
 WebRequest or NativeWebRequest
 Locale
 InputStream or one of its subclasses to access the request’s content
 OutputStream or one of its subclasses to access the response’s content
 Reader or one of its subclasses
 Writer or one of its subclasses

 The method signature must also have one of the following return types:

 ModelAndView
 Model
 Map
 View
 String - interpreted as a view name
 void,  but only if the method writes directly to the response object

 All of which should be enough for any scenario under any circumstance.

 Using @ExceptionHandler gives you the ability to perform fine grained exception handling that targets different error scenarios. In the case of the sample code, I create a new ModelAndView object and populate it with the user’s name in order to personally tell him/her that the system has lost their documents. Some may say that this is a limitation, as @ExceptionHandler is so fine-grained that you can only catch exceptions thrown by the controller that contains your @ExceptionHandler annotated method. I would disagree, if you want to catch exceptions thrown by multiple controllers in one place, then this technique is not for you and you should consider using a SimpleMappingExceptionResolver instead.

 There’s lots to consider when implementing error handling such as: what happens if there’s an error in your error handler? Should you use coarse or fine grained exception handlers? What about setting the HTTP status code? So, my next few blogs will looking into error handling further, demonstrating how to assign multiple exception classes to a single @ExceptionHandler and how to combine the exception handler notation with @ResponseStatus to fine tune your server’s HTTP status code, and may be more...
@Controller
public class ExceptionsDemoController {

private static final Logger logger = LoggerFactory.getLogger(ExceptionsDemoController.class);

@Autowired
private UserDao userDao;

/**
* Whoops, throw an IOException
*/
@RequestMapping(value = "/ioexception", method = RequestMethod.GET)
public String throwAnException(Locale locale, Model model) throws IOException {

logger.info("This will throw an IOException");

boolean throwException = true;

if (throwException) {
throw new IOException("This is my IOException");
}

return "home";
}

/**
* Catch IOException and redirect to a 'personal' page.
*/
@ExceptionHandler(IOException.class)
public ModelAndView handleIOException(IOException ex) {

logger.info("handleIOException - Catching: " + ex.getClass().getSimpleName());
return errorModelAndView(ex);
}

/**
* Get the users details for the 'personal' page
*/
private ModelAndView errorModelAndView(Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error");
modelAndView.addObject("name", ex.getClass().getSimpleName());
modelAndView.addObject("user", userDao.readUserName());

return modelAndView;
}

@RequestMapping(value = "/my404", method = RequestMethod.GET)
public String throwNoSuchRequestHandlingMethodException(Locale locale, Model model)
throws NoSuchRequestHandlingMethodException {

logger.info("This will throw a NoSuchRequestHandlingMethodException, which is Spring's 404 not found");

boolean throwException = true;

if (throwException) {
throw new NoSuchRequestHandlingMethodException("This is my NoSuchRequestHandlingMethodException", this.getClass());
}

return "home";
}

@RequestMapping(value = "/nullpointer", method = RequestMethod.GET)
public String throwNullPointerException(Locale locale, Model model) throws NoSuchRequestHandlingMethodException {

logger.info("This will throw a NullPointerException");

String str = null; // Ensure that this is null.
str.length();

return "home";
}

@ExceptionHandler({ NullPointerException.class, NoSuchRequestHandlingMethodException.class })
public ModelAndView handleExceptionArray(Exception ex) {

logger.info("handleExceptionArray - Catching: " + ex.getClass().getSimpleName());
return errorModelAndView(ex);
}

/**
* Throw a DataFormatException
*/
@RequestMapping(value = "/dataformat", method = RequestMethod.GET)
public String throwDataFormatException(Locale locale, Model model) throws DataFormatException {

logger.info("This will throw an DataFormatException");

boolean throwException = true;

if (throwException) {
throw new DataFormatException("This is my DataFormatException");
}

return "home";
}

/**
* If you add/alter in the ResponseStatus - then the server won't cope. Set
* to OK and you get a blank screen. Set to an error (300+) and you'll see
* the web server's default page - so go and fix the server configuration.
*/
@ExceptionHandler(DataFormatException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "My Response Status Change....!!")
public void handleDataFormatException(DataFormatException ex, HttpServletResponse response) {

logger.info("Handlng DataFormatException - Catching: " + ex.getClass().getSimpleName());
}


SpringMVC3 Hibernate CRUD

8 comments
Simple CRUD application using SpringMVC3, Hibernate and MySQL.
Our Application is ContactsManagements where you can view or search contacts, create new contacts, edit or delete existing contacts.

 Step#1: Create the CONTACTS Table
DROP TABLE IF EXISTS `test`.`contacts`;
CREATE TABLE  `test`.`contacts` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `address` varchar(45) DEFAULT NULL,
  `gender` char(1) DEFAULT 'M',
  `dob` datetime DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `mobile` varchar(15) DEFAULT NULL,
  `phone` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;

Step#2: Put the SpringMVC, Hibernate and their dependent jars into WEB-INF/lib folder.

Step#3: Configure SpringMVC a) Configure DispatcherServlet in web.xml

  SpringMVCHibernate
  
  
    index.jsp
  
  
  
  dispatcher
  org.springframework.web.servlet.DispatcherServlet
  1
 
 
 
  dispatcher
  *.do
 

 
  org.springframework.web.context.ContextLoaderListener
 
 
     contextConfigLocation
     classpath:applicationContext.xml
  
  
b) dispatcher-servlet.xml

 
 
 

Step#4: Configure JDBC connection parameters and Hibernate properties in config.properties
################### JDBC Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=youbusk


################### Hibernate Configuration ##########################
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
#hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true
Step#5: Configure DataSource, SessionFactory, TransactionManagement support in applicationContext.xml

 
 
 
 
 
  
 
 
 
    
     
 
    
    
 
 
     
     
               
             ${hibernate.dialect}          
             ${hibernate.show_sql}
        
     
  
 
  
 
   
 

Step#6: Configure the Labels, error messages in WEB-INF/classes/Messages.properties
App.Title=Spring MVC - Hibernate CRUD
typeMismatch.java.util.Date=Invalid Date.
dob=DOB


Step#7: Create the Entity class Contact.java
package com;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.apache.commons.lang.builder.ToStringBuilder;



@Entity
@Table(name="CONTACTS")
public class Contact
{
 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private int id;
 @Column private String name;
 @Column private String address; 
 @Column private String gender; 
 @Column private Date dob; 
 @Column private String email;
 @Column private String mobile; 
 @Column private String phone;
 
 public Contact()
 {
 }
 
 public Contact(int id, String name, String address, String gender,
   Date dob, String email, String mobile, String phone)
 {
  super();
  this.id = id;
  this.name = name;
  this.address = address;
  this.gender = gender;
  this.dob = dob;
  this.email = email;
  this.mobile = mobile;
  this.phone = phone;
 }
 @Override
 public String toString()
 {
  return ToStringBuilder.reflectionToString(this);
 }
 public int getId()
 {
  return id;
 }
 public void setId(int id)
 {
  this.id = id;
 }
 public String getName()
 {
  return name;
 }
 public void setName(String name)
 {
  this.name = name;
 }
 public String getAddress()
 {
  return address;
 }
 public void setAddress(String address)
 {
  this.address = address;
 }
 public String getGender()
 {
  return gender;
 }
 public void setGender(String gender)
 {
  this.gender = gender;
 }
 public Date getDob()
 {
  return dob;
 }
 public void setDob(Date dob)
 {
  this.dob = dob;
 }
 public String getEmail()
 {
  return email;
 }
 public void setEmail(String email)
 {
  this.email = email;
 }
 public String getMobile()
 {
  return mobile;
 }
 public void setMobile(String mobile)
 {
  this.mobile = mobile;
 }
 public String getPhone()
 {
  return phone;
 }
 public void setPhone(String phone)
 {
  this.phone = phone;
 } 
}
Step#8: Create the ContactsDAO.java which performs CRUD operations on CONTACTS table.
package com;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Harit
 *
 */
@Repository
@Transactional
public class ContactsDAO
{
 @Autowired
 private SessionFactory sessionFactory;
 
 public Contact getById(int id)
 {
  return (Contact) sessionFactory.getCurrentSession().get(Contact.class, id);
 }
 
 @SuppressWarnings("unchecked")
 public List searchContacts(String name)
 {
  Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
  criteria.add(Restrictions.ilike("name", name+"%"));
  return criteria.list();
 }
 
 @SuppressWarnings("unchecked")
 public List getAllContacts()
 {
  Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
  return criteria.list();
 }
 
 public int save(Contact contact)
 {
  return (Integer) sessionFactory.getCurrentSession().save(contact);
 }
 
 public void update(Contact contact)
 {
  sessionFactory.getCurrentSession().merge(contact);
 }
 
 public void delete(int id)
 {
  Contact c = getById(id);
  sessionFactory.getCurrentSession().delete(c);
 }

}
Step#9: Create ContactFormValidator.java which performs the validations on saving/updating a contact.
package com;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;


/**
 * @author Harit
 *
 */
@Component("contactFormValidator")
public class ContactFormValidator implements Validator
{
 @SuppressWarnings("unchecked")
 @Override
 public boolean supports(Class clazz)
 {
  return Contact.class.isAssignableFrom(clazz);
 }

 @Override
 public void validate(Object model, Errors errors)
 {
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name","required.name", "Name is required.");
 }

}
Step#10: Create ContactsControllers.java which processes all the CRUD requests.
package com;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author Harit
 *
 */

@Controller
public class ContactsControllers
{
 @Autowired
 private ContactsDAO contactsDAO;
 
 @Autowired
 private ContactFormValidator validator;
 
 @RequestMapping("/home")
 public String home()
 {
  return "home";
 }
 
 
 @InitBinder
 public void initBinder(WebDataBinder binder) 
 {
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
  dateFormat.setLenient(false);
  binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
 }
  
 @RequestMapping("/searchContacts")
 public ModelAndView searchContacts(@RequestParam(required= false, defaultValue="") String name)
 {
  ModelAndView mav = new ModelAndView("showContacts");
  List contacts = contactsDAO.searchContacts(name.trim());
  mav.addObject("SEARCH_CONTACTS_RESULTS_KEY", contacts);
  return mav;
 }
 
 @RequestMapping("/viewAllContacts")
 public ModelAndView getAllContacts()
 {
  ModelAndView mav = new ModelAndView("showContacts");
  List contacts = contactsDAO.getAllContacts();
  mav.addObject("SEARCH_CONTACTS_RESULTS_KEY", contacts);
  return mav;
 }
 
 @RequestMapping(value="/saveContact", method=RequestMethod.GET)
 public ModelAndView newuserForm()
 {
  ModelAndView mav = new ModelAndView("newContact");
  Contact contact = new Contact();
  mav.getModelMap().put("newContact", contact);
  return mav;
 }
 
 @RequestMapping(value="/saveContact", method=RequestMethod.POST)
 public String create(@ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status)
 {
  validator.validate(contact, result);
  if (result.hasErrors()) 
  {    
   return "newContact";
  }
  contactsDAO.save(contact);
  status.setComplete();
  return "redirect:viewAllContacts.do";
 }
 
 @RequestMapping(value="/updateContact", method=RequestMethod.GET)
 public ModelAndView edit(@RequestParam("id")Integer id)
 {
  ModelAndView mav = new ModelAndView("editContact");
  Contact contact = contactsDAO.getById(id);
  mav.addObject("editContact", contact);
  return mav;
 }
 
 @RequestMapping(value="/updateContact", method=RequestMethod.POST)
 public String update(@ModelAttribute("editContact") Contact contact, BindingResult result, SessionStatus status)
 {
  validator.validate(contact, result);
  if (result.hasErrors()) {
   return "editContact";
  }
  contactsDAO.update(contact);
  status.setComplete();
  return "redirect:viewAllContacts.do";
 }
 
 
 @RequestMapping("deleteContact")
 public ModelAndView delete(@RequestParam("id")Integer id)
 {
  ModelAndView mav = new ModelAndView("redirect:viewAllContacts.do");
  contactsDAO.delete(id);
  return mav;
 }
 
}
Step#11: Instead of writing the JSTL tag library declerations in all the JSPs, declare them in one JSP and include that JSP in other JSPs. taglib_includes.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
Step#12: Create the JSPs.
a)showContacts.jsp
<%@include file="taglib_includes.jsp" %>




<spring:message code="App.Title"></spring:message> 



 
Enter Contact Name      
Id Name Address Mobile
No Results found
 Edit   Delete
b) newContact.jsp
<%@include file="taglib_includes.jsp" %>



 
 <spring:message code="App.Title"></spring:message> 



Edit Contact Form

Name
DOB
Gender
Address
Email
Mobile
     
c) home.jsp
<%@include file="taglib_includes.jsp" %>


<spring:message code="App.Title"></spring:message> 



 Show Contacts 


 

d) editContact.jsp
<%@include file="taglib_includes.jsp" %>



 
 <spring:message code="App.Title"></spring:message> 



Edit Contact Form

Id
Name
DOB
Gender
Address
Email
Mobile
     
Step#13: Write the javascript file js/contacts.js containing the utility methods
function go(url)
{
 window.location = url;
}

function newContact()
{
 window.location = "saveContact.do";
}

function deleteContact(url)
{
 var isOK = confirm("Are you sure to delete?");
 if(isOK)
 {
  go(url);
 }
}

Download Complete Project
Related Posts Plugin for WordPress, Blogger...