Spring MVC with Annotations , JPA , Derby , Fileupload, SWFUpload CRUD Example

This is my attempt to create a clear tutorial on Spring MVC CRUD using JPA and Derby and a sample FileUpload with SWFUpload

I have tried to use standard file structure and naming patterns so that it will be useful in proceeding further on this base

First of all To create any Spring Application we need to configure DispatcherServlet in Servlet in Web.xml of Application so that all SpringMVC related requests goto to that servlet

Here is sample code snippet of web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Use this definition if using a Java EE 6 container This also stops Eclipse
	from complaining that 3.0 is not a valid version <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"> -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">

	<!-- The definition of the Root Spring Container shared by all Servlets
		and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/app/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>

</web-app>

Now that we have defined DispatcherServlet in Web.xml, let me define each file and its usage so that you can download and change what ever us required for you

WEB-INF
│ web.xml : Servlet Configuration Defined Here

├───spring
│ │ db.xml : DB related Beans Configured Here
│ │ root-context.xml
│ │
│ └───app
│ controllers.xml : Contrller Configuration defined here. We are using annotation so we just tell spring that use annotation handler to indefiy files
I also added a multipart resolver to handle multipart request here.
│ servlet-context.xml: Core Spring MVC Configuration file which is root file where spring MVC reads. I defined resources/view resolver/validator/and controller here

└───views
│ edit.jsp : Sample page to show edit functionaly
│ home.jsp : Welcome Page
│ list.jsp : List records page
│ upload.jsp : Simple Upload Functionality using SWFUpload is defined here

└───forms
success.jsp
upload.jsp

src/main/
│ │
│ ├───resources
│ │ │ db.properties : DB connectivity Properties to connect
│ │ │ log4j.xml : Logiing related xml
│ │ │
│ │ └───META-INF
│ │ persistence.xml : JPA Configuration file
│ │

Here is code of my File Upload Controller

/**
 *
 */
package com.linkwithweb.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.linkwithweb.spring.model.UploadBean;

/**
 * @author Ashwin Kumar
 *
 */

@Controller
@RequestMapping("/upload/")
public class UploadController {

	public UploadController() {
	}

	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute("uploadbean", new UploadBean());
		return "forms/upload";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String Uploadcreate(UploadBean uploadbean, BindingResult result) {
		System.out.println("started uploading");
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error in uploading: " + error.getCode()
						+ " - " + error.getDefaultMessage());
			}
			return "forms/upload";
		}

		// Some type of file processing...
		System.err.println("-------------------------------------------");

		System.err.println("Test uploading file: "
				+ uploadbean.getFiledata().getOriginalFilename());
		System.err.println("-------------------------------------------");		return "forms/success";
	}
}

Note: You have define Multipart resolver bean of commons file upload inorder to parse file upload requests

	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="100000" />
	</bean>

Code can be found at following SVN location
https://linkwithweb.googlecode.com/svn/trunk/SpringTutorials/SpringApp

Once downloaded run ” mvn jetty:run” to test the application at follwoing URL

http://localhost:8080/SpringApp/

http://localhost:8080/SpringApp/spring/upload/

Advertisements

2 thoughts on “Spring MVC with Annotations , JPA , Derby , Fileupload, SWFUpload CRUD Example

  1. Very nicely done. I was up and running quickly working from this. The only thing I might add is some code sending along the jsessionid to prevent issues with the upload call returning a 302 error, especially if you’re using Spring Security. Thanks a lot for posting, it was really a big help.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s