Wednesday, August 14, 2013

Spring 3 MVC + Hibernate 4 + JdbcTemplate + Partial REST controller (Part 1)

This is post serves as a reference point to quickly setup a Java web application with Spring 3 MVC, Hibernate 4, JdbcTemplate and a partial REST controller. We'll be consuming and responding JSON content via the REST controllers.

I'm using Eclipse as the IDE and will be connecting to MySQL database.

Let's start off with the libraries:

  • antlr-2.7.7.jar
  • aopalliance.jar
  • bonecp-0.7.1.RELEASE.jar
  • commons-lang3-3.1.jar
  • commons-logging-1.1.3.jar
  • dom4j-1.6.1.jar
  • guava-14.0.1.jar
  • hibernate-commons-annotations-4.0.2.Final.jar
  • hibernate-core-4.2.4.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • jackson-annotations-2.2.0.jar
  • jackson-core-2.2.0.jar
  • jackson-databind-2.2.0.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.1.Final.jar
  • mysql-connector-java-5.1.26-bin.jar
  • slf4j-api-1.7.5.jar
  • slf4j-simple-1.7.5.jar
  • spring-aop-3.2.3.RELEASE.jar
  • spring-beans-3.2.3.RELEASE.jar
  • spring-context-3.2.3.RELEASE.jar
  • spring-core-3.2.3.RELEASE.jar
  • spring-expression-3.2.3.RELEASE.jar
  • spring-jdbc-3.2.3.RELEASE.jar
  • spring-orm-3.2.3.RELEASE.jar
  • spring-tx-3.2.3.RELEASE.jar
  • spring-web-3.2.3.RELEASE.jar
  • spring-webmvc-3.2.3.RELEASE.jar

We'll continue to configure the web app by specifying the web.xml:





  
    contextConfigLocation    /WEB-INF/*ctx.xml  

  
    org.springframework.web.context.ContextLoaderListener
  

  
    api
    org.springframework.web.servlet.DispatcherServlet
    1
  

  
    api
    /api/*
  

  
    /errors/error.jsp
  



Next is to create the application context XML. We'll only have 3 bean definitions in the app-ctx:





 
  
  
  
  
  
  
  
  
  
  
  
  
 

 
  

  
    
      org.hibernate.dialect.MySQL5Dialect
      true
    
  
  
 
 
 
  
 
 



Now for the api-servlet.xml. No bean definition in this file as everything is annotation based.




 

 

 



We also have a single JSP to handle errors in errors/error.jsp. This is as bare as it gets:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




ERROR



<%
out.println(request.getAttribute("javax.servlet.error.message"));
out.println(request.getAttribute("javax.servlet.error.status_code"));

%>



This concludes basic setup for the webapp. Next part will include Java classes for the controller and error handling.

1 comment:

SmithWorks said...

Throughout this example, xsi:schemalocation is used. I find that to keep Eclipse/STS happy, it seems to need to be be xsi:schemaLocation?(note upper case "L".