not getting model filled from jsp in spring mvc - java

Same error even adding #ModelAttributeI am not able to get the model class filled while clicking on button on jsp. In Database a new field is created but value are going null(Because model is not getting filled).
Please help me out on this.
Thanks in advance.
My Model class is:
package model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "conversion")
public class Conversion {
#Id
#GeneratedValue
private int conversionId;
#Column(name = "conversionFrom")
private String conversionFrom;
#Column(name = "conversionFromValue")
private int conversionFromValue;
#Column(name = "conversionTo")
private String conversionTo;
#Column(name = "conversionToValue")
private int conversionToValue;
#Column(name = "conversionDate")
private Date conversionDate;
public int getConversionId() {
return conversionId;
}
public void setConversionId(int conversionId) {
this.conversionId = conversionId;
}
public String getConversionFrom() {
return conversionFrom;
}
public void setConversionFrom(String conversionFrom) {
this.conversionFrom = conversionFrom;
}
public int getConversionFromValue() {
return conversionFromValue;
}
public void setConversionFromValue(int conversionFromValue) {
this.conversionFromValue = conversionFromValue;
}
public String getConversionTo() {
return conversionTo;
}
public void setConversionTo(String conversionTo) {
this.conversionTo = conversionTo;
}
public int getConversionToValue() {
return conversionToValue;
}
public void setConversionToValue(int conversionToValue) {
this.conversionToValue = conversionToValue;
}
public Date getConversionDate() {
return conversionDate;
}
public void setConversionDate(Date conversionDate) {
this.conversionDate = conversionDate;
}
}
My controller method is:
#RequestMapping("/saveConversion")
public ModelAndView saveConversion(HttpServletRequest request, HttpServletResponse response, Model model,
Conversion conversion) throws ServletException, IOException, ParseException {
System.out.println("In saveConversion");
Boolean boolean1 = serviceDao.setConversion(conversion);
if (boolean1) {
model.addAttribute("conversionSaved", "Conversion saved successfully!");
} else {
model.addAttribute("conversionSaved", "Conversion Not saved!");
}
return new ModelAndView("setConversion");
}
My Jsp is:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%#page import="model.Test"%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Lexis Nexis Admin Set Conversion Page</title>
<!--css and js starts-->
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<script src="jQueryAssets/jquery_lib.js"></script>
<script>
function SaveConversion() {
var params = $("#Conversion_form").serialize();
alert(params);
$.ajax({
method : "POST",
url : "saveConversion",
data : {
'params' : params
},
success : function(result) {
alert(result);
$("#responseDiv").html(result);
messageDisplay();
return false;
}
})
}
function messageDisplay() {
alert("${conversionSaved}");
}
</script>
</head>
<body onload="clearData()">
<div class="mainpage">
<div class="add_admin_form">
<form id="Conversion_form" method="post" name="Conversion">
<div class="add_admin_form_label">
<spring:message code="CONVERSION_FROM" />
</div>
<div class="add_admin_form_field">
<select name="conversionFrom" id="conversionFrom" class="dropdown2">
<option value="USD"><spring:message code="USD" /></option>
<option value="INR"><spring:message code="INR" /></option>
</select> <input name="conversionFromValue" id="conversionFromValue"
type="text" class="textbox1" value="${conversion.conversionFromValue}" required />
</div>
<div class="add_admin_form_label">
<spring:message code="CONVERSION_TO" />
</div>
<div class="add_admin_form_field">
<select name="conversionTo" id="conversionTo" class="dropdown2">
<option value="INR"><spring:message code="INR" /></option>
<option value="USD"><spring:message code="USD" /></option>
</select> <input name="conversionToValue" id="conversionToValue" type="text"
class="textbox1" required />
</div>
<div class="add_admin_form_field">
<input type="button" value="" class="create"
onclick="SaveConversion()" />
</div>
</form>
</div>
</div>
<div class="clear"></div>
<div class="clear"></div>
</body>
</html>
My hibernate.cfg.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated file - Do not edit! -->
<hibernate-configuration>
<!-- a SessionFactory instance listed as /jndi/name -->
<session-factory>
<!-- User / Password -->
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- Database Settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- for performance reasons changed to MyISAM from org.hibernate.dialect.MySQLInnoDBDialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/quotebuilder</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<!-- Database Scheme Auto Update -->
<property name="hbm2ddl.auto">update</property>
<!-- properties -->
<property name="show_sql">true</property>
<property name="use_outer_join">false</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory</property>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!-- <property name="connection.provider_class ">org.hibernate.connection.C3P0ConnectionProvider</property> -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.generate_statistics">false</property>
<property name="hibernate.cache.use_structured_entries">false</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.timeout">100</property>
<!-- mapping files -->
<mapping class="model.User" />
<mapping class="model.Quotation" />
<mapping class="model.CustomerSize" />
<mapping class="model.CustomerSegment" />
<mapping class="model.Admin" />
<mapping class="model.Customer" />
<mapping class="model.CustomerTypeDiscount" />
<mapping class="model.EmployeeLevelDiscount" />
<mapping class="model.Product" />
<mapping class="model.ProductVolumeDiscount" />
<mapping class="model.TitleAuthorTag" />
<mapping class="model.TitleContentTag" />
<mapping class="model.Conversion" />
</session-factory>
</hibernate-configuration>
Dispatcher-servlet is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="login" class="controller.LoginController" />
<bean id="levelManagement" class="controller.LevelManagementController" />
<bean id="user" class="controller.UserController" />
<bean id="home" class="controller.HomeController" />
<bean id="report" class="controller.ReportController" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames" value="WEB-INF/properties/messages" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml is:
<web-app 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"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
pom.xml is:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.logiquebrain</groupId>
<artifactId>QuoteBuilderAdmin</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>QuoteBuilderAdmin Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- Hibernate core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.2.Final</version>
</dependency>
<!-- optional -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-osgi</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-proxool</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-infinispan</artifactId>
<version>5.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.0.2.Final</version>
</dependency>
<!-- Add on 03-12-2015 -->
<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version> </dependency> <dependency> <groupId>dom4j</groupId>
<artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency>
<groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId>
<version>1.1.1</version> </dependency> <dependency> <groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId> <version>3.2.1</version> </dependency>
<dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version>
</dependency> <dependency> <groupId>asm</groupId> <artifactId>asm</artifactId>
<version>3.1</version> </dependency> <dependency> <groupId>javax.transaction</groupId>
<artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency>
<groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId>
<version>2.5.1</version> </dependency> -->
<!-- Add on 03-12-2015 -->
<!-- Add on 04-12-2015 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<!-- Add on 04-12-2015 -->
<!-- Add on 07-12-2015 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
<!-- Add on 07-12-2015 -->
</dependencies>
<build>
<finalName>QuoteBuilderAdmin</finalName>
<!-- Add on 07-12-2015 -->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
<!-- Add on 07-12-2015 -->
</build>
</project>

do the changes as mentioned by #alan and also make following changes to your js function:
function SaveConversion() {
var params = $("#Conversion_form").serialize();
alert(params);
$.ajax({
method : "POST",
url : "saveConversion",
data : params, //this line is changed
success : function(result) {
alert(result);
$("#responseDiv").html(result);
messageDisplay();
return false;
}
})
}
the js function as per the question was sending only one parameter "param" which had value of serialized form value. After making above change it should be working. I have verified the same using network tab of the browser. You can see it for yourself if needed.

If you want to Spring to automatically bind the submitted parameters to a Conversion instance then you need to use the #ModelAttribute annotation in your method signature.
#RequestMapping("/saveConversion")
public ModelAndView saveConversion(#ModelAttribute Conversion conversion, Model model) throws ServletException, IOException, ParseException {
System.out.println("In saveConversion");
Boolean boolean1 = serviceDao.setConversion(conversion);
if (boolean1) {
model.addAttribute("conversionSaved", "Conversion saved successfully!");
} else {
model.addAttribute("conversionSaved", "Conversion Not saved!");
}
return new ModelAndView("setConversion");
}
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-method-args
An #ModelAttribute on a method argument indicates the argument should
be retrieved from the model. If not present in the model, the argument
should be instantiated first and then added to the model. Once present
in the model, the argument’s fields should be populated from all
request parameters that have matching names. This is known as data
binding in Spring MVC, a very useful mechanism that saves you from
having to parse each form field individually.

Related

Unable ot get openJPA working with Tomcat 8

I'm trying to get OpenJPA working with Tomcat 8 but have been unable, it throws the error:
org.apache.openjpa.persistence.ArgumentException: The persistence provider is
attempting to use properties in the persistence.xml file to resolve the
data source. A Java Database Connectivity (JDBC) driver or data source class name
must be specified in the openjpa.ConnectionDriverName or
javax.persistence.jdbc.driver property. The following properties
are available in the configuration:
"org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl#2655aabb".
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
...servlet stuff...
<resource-ref>
<description>Database</description>
<res-ref-name>jdbc/webservice</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
My context.xml (I verified this datasource works by doing a connection via InitialContext, etc in a servlet):
<?xml version="1.0" encoding="utf-8"?>
<Context>
<Resource name="jdbc/webservice" auth="Container"
type="javax.sql.DataSource"
maxActive="8"
removeAbandoned="true"
removeAbandonedTimeout="60"
logAbandoned="true"
validationQuery="SELECT 1"
username="dev" password="mypass"
url="jdbc:mysql://127.0.0.1:3306/mydb"
driverClassName="com.mysql.jdbc.Driver">
</Resource>
<Resource name="BeanManager"
auth="Container"
type="javax.enterprise.inject.spi.BeanManager"
factory="org.jboss.weld.resources.ManagerObjectFactory"/>
</Context>
My persistence.xml (I also tried every diff combo of the properties and data-source elements. I also tried "RESOURCE_LOCAL"):
<?xml version="1.0" encoding="UTF-8"?>
<persistence
version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="TestOpenJPAPersistence" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>java:comp/env/jdbc/webservice</jta-data-source>
<non-jta-data-source>java:comp/env/jdbc/webservice</non-jta-data-source>
<
<properties>
<!--
I tried leaving these out, leaving them in and all combinations.
I also tried it with the jdbc url, username, password in properties too.
-->
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver"/>
<property name="openjpa.ConnectionFactoryProperties" value="MaxActive=10,MaxIdle=5,MinIdle=2,MaxWait=1800000"/>
<property name="openjpa.Log" value="org.apache.openjpa.log, DefaultLevel=DEBUG, Runtime=INFO, Tool=INFO, SQL=TRACE"/>
<property name="openjpa.DynamicEnhancementAgent" value="false" />
<property name="openjpa.RuntimeUnenhancedClasses" value="unsupported" />
</properties>
</persistence-unit>
</persistence>
My pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>TestWebSocket</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<!-- Tell Maven what language version to use -->
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.enterprise/cdi-api -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
</dependency>
<!-- Enables the annotations, etc needed -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<exclusions>
<exclusion>
<groupId>javax.exterprise</groupId>
<artifactId>cdi-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Our jersey libs -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.25.1</version>
</dependency>
<!-- CDI to JAX-RS Binding -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers.glassfish/jersey-gf-cdi-ban-custom-hk2-binding -->
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>2.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld.servlet/weld-servlet-core -->
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet-core</artifactId>
<version>3.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld/weld-core-impl -->
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core-impl</artifactId>
<version>3.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
</project>
My Servlet:
package com.testjpa;
import com.testpush.TestEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
#WebServlet("/jpa")
public class JPAServlet extends HttpServlet
{
#PersistenceUnit(unitName = "TestOpenJPAPersistence")
EntityManagerFactory persistenceFactory;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
EntityManager persistenceManager = null;
String result = "Not found";
try
{
//I need to do this as otherwise the factory is null
persistenceFactory = Persistence.createEntityManagerFactory( "TestOpenJPAPersistence" );
//This line throws the error
persistenceManager = persistenceFactory.createEntityManager();
User user = persistenceManager.find( User.class, 9 );
if ( user != null )
{
result = user.getName();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if ( persistenceManager != null )
{
persistenceManager.close();
}
}
resp.getWriter().println( result );
}
}
Looking at your source code, I found the problem : your persistence.xml is located in src/main/webapp/META-INF instead of src/main/resources/META-INF.
Move it to src/main/resources/META-INF and remove the javax.persistence.jdbc.driver property and it will work.

406 Not acceptable error when returning JSON in Spring MVC

I am working on application which will just used as a restful services and the response has to be returned as JSON.y p
I am on Spring MVC and following this article to achieve the same
https://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/
I have added Jackson jar in my POM, enabled response body and mvc-annotation-driven annotation.
But still on firing the url i get 406 Not acceptable error.
I have tried firing with a rest client and adding request headers for Content-Type and Accept with "application/json".
Below is my POM with the dependencies part
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.10</version>
</dependency>
My spring config file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.sap.cf.casestudy.controller" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
My controller code
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sap.cf.casestudy.domain.Employee;
#Controller
#RequestMapping("/employee")
public class EmployeeController {
#RequestMapping(method = RequestMethod.GET ,headers="Accept=application/json")
public #ResponseBody Employee getEmployee() {
List<Employee> empList = getEmployeeData();
return empList.get(0);
//return "employeelist";
}
private List<Employee> getEmployeeData(){
List<Employee> employeeList = new ArrayList<Employee>();
Employee emp1 = new Employee();
emp1.setFirstName("Saurav");
emp1.setLastName("Sarkar");
employeeList.add(emp1);
Employee emp2 = new Employee();
emp2.setFirstName("John");
emp2.setLastName("Doe");
employeeList.add(emp1);
return employeeList;
}
}
In addition i have a POJO of employee class with firstname and lastname as private methods and setter/getter as public methods.
Best Regards,
Saurav
Spring 4.3.10: I used the below settings to resolve the issue.
Step 1: Add the below dependencies
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.7</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Step 2: Add the below in your MVC DispatcherServlet context configuration:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false"/>
<property name="favorParameter" value="true"/>
<property name="ignoreAcceptHeader" value="false" />
</bean>
Since spring 3.2, as per the default configuration favorPathExtension is set as true, because of this if the request uri have any proper extensions like .htm spring will give priority for the extension. In step 2 I had added the contentNegotiationManager bean to override this.
I could resolve the problem with my above code itself.
Problem was the jackson mapper jar was not present in the classpath.
So it was not working.
In Eclipse For Maven projects you have to force update such that the jar can come in the classpath.
Ideally there should been an error from the spring framework about the class not being loaded. The error itself was misleading.
Best Regards,
Saurav
My simple setting. hope this helps a little bit
pom.xml
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
servlet-context.xml
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<context:component-scan base-package="com.urong.sample" />
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven>
<mvc:message-converters>
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<beans:property name="supportedMediaTypes">
<beans:list>
<beans:value>text/html;charset=UTF-8</beans:value>
</beans:list>
</beans:property>
</beans:bean>
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<mvc:resources location="/resources/" mapping="/resources/**" />
<mvc:default-servlet-handler />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<!-- Your Resolves -->
Controller
#RequestMapping(value = "/call", method = RequestMethod.POST)
public #ResponseBody String callTest(#RequestBody CompanyLocation location) {
// use location. this sample object
return "your return String";
}
client(my javascript)
function callTest() {
var companyIdx = $('#companyIdx').val();
var locationIdx = $('#locationIdx').val();
var data = {
idx : locationIdx,
postCode : $('#postCode').val(),
address : $('#address').val(),
detailAddress : $('#detailAddress').val(),
tel : $('#tel').val(),
fax : $('#fax').val(),
email : $('#email').val(),
language : $("#language").val(),
latitude : $('#latitude').val(),
longtitude : $('#longtitude').val()
};
data = JSON.stringify(data);
$.ajax({
url : "/sample/call,
type : 'POST',
data : data,
contentType : 'application/json',
success : function(response) {
// use response.
},
error : function(request, status, error) {
},
complete : function(data) {
}
});
}

Error In Maven Spring 3 Dynamic Application

i am using maven, spring 3 for dynamic project. I am getting error at <bean name="/hello.cs" class="com.maven.controller.HelloController"/> as Multiple annotations found at this line:
- Class 'com.maven.controller.HelloController'
Project Structure
Web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.cs</url-pattern>
</servlet-mapping>
</web-app>
Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="/hello.cs" class="com.maven.controller.HelloController"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
index.jsp
<jsp:forward page="WEB-INF/jsp/home.jsp"></jsp:forward>
home.jsp
<form action="./hello.cs" method="post">
<div>
<div>
User Name:<input type="text" name="name"/>
</div>
<div>
Password: <input type="password" name="pass"/>
</div>
<div>
<input type="submit" value="Login"/>
</div>
<div>
<p style="color: red">${msg}</p>
</div>
</div>
</form>
HelloController
package com.maven.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.Controller;
public class HelloController extends AbstractController{
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
String name = req.getParameter("name");
String pwd = req.getParameter("pass");
Map<String, String> m = new HashMap<String, String>();
if(name.equalsIgnoreCase("xyz") && pwd.equalsIgnoreCase("123")){
m.put("msg", "welcome mr. "+req.getParameter("name"));
return new ModelAndView("success", m);
} else {
m.put("msg", "Invalid");
return new ModelAndView("home");
}
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javatpoint</groupId>
<artifactId>CubeGeneratorWeb</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>CubeGeneratorWeb Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>CubeGeneratorWeb</finalName>
</build>
</project>
Error:
EDIT: It says class 'com.maven.controller.HelloController' not found.
I see that you have put your com.maven.controller.HelloController.java file under src\main\resources folder.
It should be under src\main\java folder. So the hierarchy should be like
src
|-main
|-java
|-com
|-maven
|-controller
|-HelloController.java
The reason is the directory structure followed by maven detects java files only if it's placed under this hierarchy src\main\java, if you are using default configuration.
Can you right click on project and go to Properties > Java Build Path > Source and check whether src\main\java entry is there in the build path list or not? If not add it and try again.
After lots of struggle i got the answer, i had error in spring.xml file. check the solutions.
i need to add below code only in spring.xml file.
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
previously i was using below code
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
for above code i need to change pom.xml file, i mean need to add more dependency.
so this is my final spring.xml file for this question only.
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean name="/hello.sa" class="com.maven.controller.HelloController"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>

Values are getting deleted from the database when the application is run again

I have a made a sample application in Spring + Hibernate + ZK framework.
In the Hibernate configuration file I have kept the property hbm2ddl.auto in "update" mode. Still Whenever I run the application again I dont get the values persisted earlier.
Following are several configuration files for reference:
BeanLocations.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Database Configuration -->
<import resource="../database/DataSource.xml"/>
<import resource="../database/Hibernate.xml"/>
<!-- Auto scan the components -->
<context:component-scan
base-package="com.nagarro" />
</beans>
DataSource.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>properties/database.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- <property name="hibernate.current_session_context_class" value = "${hibernate.current_session_context_class}" /> -->
</bean>
</beans>
Hibernate.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.nagarro.model.ItemAttribute</value>
<value>com.nagarro.model.ItemAttributeGroup</value>
</list>
</property>
</bean>
</beans>
Controller/ Viewmodel class
public class ItemAttributeRenderer {
/*
* The Logger reference variable used for Logging.
*/
static private final Logger LOG = LoggerFactory.getLogger(ItemAttributeRenderer.class);
#Autowired
private ItemAttributeService itemAttrService;
private List<ItemAttribute> itemList = new ArrayList<ItemAttribute>();
private void prepareAndSaveItemAttributeData(){
ItemAttribute item = null;
int counter;
for(int index = 0; index < 5; index++){
counter = index+1;
item = new ItemAttribute("Item "+counter, "Attirbute Value"+counter, "Qualifier Value"+counter);
itemAttrService.save(item);
}
}
/**
* #return the itemList
*/
public List<ItemAttribute> getItemList() {
ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring/config/BeanLocations.xml");
itemAttrService = (ItemAttributeService)appContext.getBean("itemAttrService");
prepareAndSaveItemAttributeData();
itemList = itemAttrService.getItemAttributeList();
return itemList;
}
#Command
public void save(){
for(ItemAttribute item : itemList){
itemAttrService.update(item);
}
}
/**
* #param itemList the itemList to set
*/
public void setItemList(List<ItemAttribute> itemList) {
this.itemList = itemList;
}
/**
* #return the itemAttrService
*/
public ItemAttributeService getItemAttrService() {
return itemAttrService;
}
/**
* #param itemAttrService the itemAttrService to set
*/
public void setItemAttrService(ItemAttributeService itemAttrService) {
this.itemAttrService = itemAttrService;
}
}
View file:
<?page title="Result"?>
<zk>
<custom-attributes center="${arg.center }" />
<window apply="org.zkoss.bind.BindComposer"
viewModel="#id('vm') #init('com.nagarro.viewmodel.ItemAttributeRenderer')"
title="Result Window" border="normal">
<div>
<grid>
<rows>
<row>
<listbox model="#bind(vm.itemList)">
<listhead>
<listheader label="Item Name"
style="text-align:center;">
</listheader>
<listheader label="Attribute Value"
style="text-align:center;">
</listheader>
<listheader label="Qualifier Value"
style="text-align:center;">
</listheader>
</listhead>
<template name="model" var="item">
<listitem value="${item }">
<listcell label="#load(item.name)"
style="text-align:center;">
</listcell>
<listcell style="text-align:center;">
<textbox value="#bind(item.attributeValue)"
style="text-align:center;"/>
</listcell>
<listcell
label="#load(item.qualifierValue)"
style="text-align:center;">
</listcell>
</listitem>
</template>
</listbox>
</row>
</rows>
</grid>
</div>
<div style="text-align:right; padding:10px;">
<button label="Save" mold="trendy"
onClick="#command('save')">
</button>
</div>
</window>
</zk>
Service class
#Service("itemAttrService")
public class ItemAttributeServiceImpl implements ItemAttributeService{
#Autowired
ItemAttributeDao itemAttrDao;
public void setItemAttrDao(ItemAttributeDao itemAttrDao) {
this.itemAttrDao = itemAttrDao;
}
public void save(ItemAttribute item){
itemAttrDao.save(item);
}
public void update(ItemAttribute item){
itemAttrDao.update(item);
}
public void delete(ItemAttribute item){
itemAttrDao.delete(item);
}
public ItemAttribute findByItemAttributeName(String name){
return itemAttrDao.findByItemAttributeName(name);
}
public List<ItemAttribute> getItemAttributeList(){
return itemAttrDao.getItemAttributeList();
}
}
DAO class
#Repository("itemAttrDao")
public class ItemAttributeDaoImpl extends CustomHibernateDaoSupport implements ItemAttributeDao {
public void save(ItemAttribute itemAttribute) {
getHibernateTemplate().save(itemAttribute);
//getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
}
public void update(ItemAttribute itemAttribute) {
getHibernateTemplate().update(itemAttribute);
//getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
}
public void delete(ItemAttribute itemAttribute) {
getHibernateTemplate().delete(itemAttribute);
//getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
}
public ItemAttribute findByItemAttributeName(String name) {
List list = getHibernateTemplate().find("from ItemAttribute where name=?",name);
if(list == null){
}else if(list.isEmpty()){
}
return (ItemAttribute)list.get(0);
}
public List<ItemAttribute> getItemAttributeList() {
List<ItemAttribute> itemList = getHibernateTemplate().find("from ItemAttribute ");
return itemList;
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.abc</groupId>
<artifactId>ZKSpringHibernateExample</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringHibernateExample</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>java.net</id>
<url>http://download.java.net/maven/2/</url>
</repository>
</repositories>
<properties>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- MySQL database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- Hibernate framework -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- Hibernate library dependecy start -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<!-- Hibernate library dependecy end -->
<!-- ZK Dependency start -->
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkplus</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zhtml</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkbind</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zul</artifactId>
<version>6.0.0</version>
</dependency>
<!-- ZK Dependency Ends -->
</dependencies>
</project>
My problem is When I run the application again all the data that was saved earlier vanishes even though I have set the hbm2ddl.auto property to update mode.
I have set my show_sql property as "true" to check the queries that are getting fired but there are no delete queries which are getting fired.
Is there any other important thing that I am missing here.
See comments and read Hibernate manual here
<property name="hbm2ddl.auto">update</property>
setting above property Drop and re-create the database schema on startup
consider below comments from hibernate manual.
Hibernate's automatic session management for persistence contexts is particularly useful in this context. The hbm2ddl.auto option turns on automatic generation of database schemas directly into the database. This can also be turned off by removing the configuration option, or redirected to a file with the help of the SchemaExport Ant task.
hbm2ddl.auto is for the validation of the database schema, which doesn't have any meaning here.
You have to commit your values, if not they are not permanently stored in the database.
I found the solution. there were a lot of messy project dependencies in my Tomcat so I deleted that instance of Tomcat and reconfigured it for my project. Then I cleaned my project and now everything is working fine as it should be. Thanks for taking time to post the answers.

Spring REST MultipartFile file is always null

I'm trying to set up a simple upload with html and Spring 3.0.6 using REST services. I've followed the tutorial online but the MultipartFile parameter is always null. Here's the config and code:
application-context.xml:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2000000"/>
</bean>
pom.xml:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
html:
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="/site/restServices/artworkUpload/" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
REST Controller:
#POST
#Path("/artworkUpload")
public String uploadFile(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {
try {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
} else {
return "redirect:uploadFailure";
}
}
catch (Exception ex)
{
}
return null;
}
I copied the example from Spring's tutorial but no matter what I change, the file parameter is always null. "name" will have the value in the text box but file will be null.
I have also tried using Jersey and I receive the InputStream for the file but the FormDataContentDisposition is null so I can't determine the file type.
This is running on Jetty as well.
What am I missing?
As I remember I solved same issue by putting additional libs to my build path:
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
I hope this will help you.
Edit.
Ok. At last I had time for this issue. First of all, why do you use standart java features for building rest service (annotations #POST, #Path)? Because with Spring it is better to use spring MVC futures for REST. There is a lot of information about this in internet. Here is special part in reference documentation. Also here is good article on IBM site. Also very good description on how to build REST controller with Spring MVC is in Spring in Action (last 3-d edition).
Here how I have implemented simple file uploading functionality:
Rest controller:
#Controller
#RequestMapping("/rest/files")
public class FilesController {
...
#RequestMapping(value="/rest/files", method=RequestMethod.POST)
public String uploadFile(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {
try {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
} else {
return "redirect:uploadFailure";
}
}
catch (Exception ex)
{
}
return "/testFileDownload";
}
}
html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test file upload</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="rest/files" enctype="multipart/form-data">
<input type="text" name="name" /> <input type="file" name="file" /> <input
type="submit" />
</form>
</body>
</html>
View resolver configuration in dispatcher-servlet.xml:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="file" value="multipart/form-data"/>
<entry key="html" value="text/html"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>
I hope I'm not wasted my time and this is still necessary for you. )
EDIT 2
Here is very good tutorial where described how to build RESTful web service with Spring 3.1.
It helped me to connect this library:
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
All libs:
<dependencies>
<!-- Spring 3 MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<!-- Apache Commons file upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- JSTL for c: tag -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
See http://viralpatel.net/blogs/spring-mvc-multiple-file-upload-example/

Categories

Resources