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

SWFUpload and Java Servlet Example

I have been trying to find out one good upload client over the web and it really took 3 days to me to nail down one which one best.

SWFUpload seems to be best library available as of today. I dont see they implementing java examples. Here is my attempt provide a java sample for it

This example will implement basic file upload with cancel and manual upload trigger functionality with servlet in backend

Here is sample client code

		

var swfu;

window.onload = function() {
	var settings = {
		flash_url : "swfupload/swfupload.swf",
		upload_url: "Upload",
		file_size_limit : "100 MB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : 100,
		file_queue_limit : 0,
		custom_settings : {
			progressTarget : "fsUploadProgress",
			cancelButtonId : "btnCancel"
		},
		debug: false,

		// Button settings
		button_image_url: "swfupload/TestImageNoText_65x29.png",
		button_width: "95",
		button_height: "29",
		button_placeholder_id: "spanButtonPlaceHolder",
		button_text: 'Browse Files',
		button_text_style: ".theFont { font-size: 22; }",
		button_text_left_padding: 2,
		button_text_top_padding: 3,
		
		// The event handler functions are defined in handlers.js
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess
	};

	swfu = new SWFUpload(settings);
    };


    function handleUpload(){
     var emailid = document.getElementById("email").value;
   	 swfu.setPostParams({ email:emailid });
   	 //swfu.setUploadURL("CommonsFileUploadServlet?test=234");
   	 swfu.startUpload();
 }

Here is sample screenshot

SWFUploadExample

Try downloading code from SVN from follwong location

https://linkwithweb.googlecode.com/svn/trunk/Utilities/FlashFileUpload

Make sure you have maven installed on machine before executing the below command
After downloading just run “mvn jetty:run”

and open this URL to test http://localhost:8080/FileUpload/