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/
Related
I am learning spring MVC. This is a basic code which I found online and trying to run locally. I have added all the dependencies but I am still getting this error:
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Here is the code:
This is the landing page which contains the form. On submit, controller will be called.
index.jsp
<html>
<body>
<form action="hello">
UserName : <input type="text" name="name"/> <br><br>
Password : <input type="text" name="pass"/> <br><br>
<input type="submit" name="submit">
</form>
</body>
</html>
This is the maven xml which has the spring dependencies.
pom.xml
Added the below two dependencies:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
This is the controller. Login is successful when password is 'admin'.
HelloController.java
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HelloController {
#RequestMapping("/hello")
public String display(HttpServletRequest req,Model m)
{
//read the provided form data
String name=req.getParameter("name");
String pass=req.getParameter("pass");
if(pass.equals("admin"))
{
String msg="Hello "+ name;
//add a message to the model
m.addAttribute("message", msg);
return "viewpage";
}
else
{
String msg="Sorry "+ name+". You entered an incorrect password";
m.addAttribute("message", msg);
return "errorpage";
}
}
}
web.xml
<web-app>
<display-name>SpringMVC</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
spring-servlet.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Provide support for component scanning -->
<context:component-scan base-package="com.javatpoint" />
<!--Provide support for conversion, formatting and validation -->
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
viewpage.jsp
<html>
<body>
${message}
</body>
</html>
errorpage.jsp
<html>
<body>
${message}
<br><br>
<jsp:include page="/index.jsp"></jsp:include>
</body>
</html>
In your web.xml <context:component-scan base-package="com.javatpoint" />,but I don't see package com.javatpoint; in your HelloController.You need to create a package and put your contorller in it and set it up in web.xml.
Try to create com.javatpoint package and put your controller in it.
And you also set <property name="prefix" value="/WEB-INF/jsp/"></property> you need to put your viewpage.jsp and errorpage.jsp in /WEB-INF/jsp. I don't konw whether you create jsp directory in WEB-INF.
Sometimes controller can't find your jsp cause 404.
I create a project using your code,I work well.
I don't know how to solve the problem. Googled it for hours without success:
simple example:
my form in jsp
<form method="post" action="/asd" enctype="multipart/form-data">
<input type="file" class="file" name="file"/>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<input type="submit" value="Upload">
</form>
my Controller's method
#RequestMapping(value = "/asd", method = RequestMethod.POST)
public String handleFileUpload(
#RequestParam("file") MultipartFile file){
System.out.print(file);
return "string";
}
My context xml file
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
</bean>
I have in my pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version> <!-- makesure correct version here -->
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
I even added allowCasualMultipartParsing="true" to every context.xml of my server as below:
<Context reloadable="true" allowCasualMultipartParsing="true">
but the error still occurs and I don't know what I am doing wrong:
HTTP Status 400 – Bad Request
Type Status Report
Message Required MultipartFile parameter 'file' is not present
Description The server cannot or will not process the request due to
something that is perceived to be a client error (e.g., malformed
request syntax, invalid request message framing, or deceptive request
routing).
Apache Tomcat/8.5.12
Try this,
Add bellow filters in your web.xml file
Web.xml
<!-- Support for File Upload And Download -->
<filter>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter- class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And also in your context file use filterMultipartResolver instead of multipartResolver because of Spring Security dependency as bellow
<!-- Support For File Upload And Download -->
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000000" />
</bean>
And yes Cheerssssssss!!!!!!!!
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.
Hello i'm new to spring and i'm receiving a 404 error when attempting to use spring boot. When attempting to view the url in the browser i keep getting a 404 error. Please could someone assist and point me to what is wrong. I placed a debugger in the controller to print HH but i observed it never goes into the controller as it fails to print "HH" on the console.
I also noticed this from console:
:50.894 INFO 11249 --- [lication.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-11-15 07:11:50.894 INFO 11249 --- [lication.main()] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.
Below is my controller:
#RestController
public class TestController {
#RequestMapping(value="/person")
public String intro(){
System.out.println("HH");
return "index";
}
}
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>org.springExample.www</groupId>
<artifactId>Hotel-Management</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
MainApplication.java:
#SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
index.html is defined in src/main/resources/templates:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initialscale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5
elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the
page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/
3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/
1.4.2/respond.min.js"></script>
<![endif]-->
<style>
.box {
background-color:#d3d3d3
}
</style>
</head>
<body>
<h1>Hello, world!</h1>
<div class="container">
<div class="row">
<div class="col-md-6 box">Content</div>
<div class="col-md-6 box">Content</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/
jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" integrity="sha512-K1qjQ+NcF2TYO/eI3M6v8EiNYZfA95pQumfvcVrTHtwQVDG+aHRqLi/ETn2uB+1JqwYqVG3LIvdm9lj6imS/pQ==" crossorigin="anonymous"></script>
</body>
</html>
There a few things to look at:
Use #Controller rather than #RestController. The first is designed to handle views, the second is designed to return raw data.
Move the views to src/main/java/webapp/WEB-INF/. This is the conventional location for views, rather than /src/main/resources.
Change the return value of the intro() method from index to templates/index. The entire path to the view matters.
Add a class annotated with #Configuration that defines a ViewResolver bean that looks for .html views (see this answer).
My current code:
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST, headers = "Accept=*")
public void uploadFile(#RequestParam(value = "file") MultipartFile multipartFile,
Model model, HttpServletRequest request, HttpServletResponse response) {
String fileName = multipartFile.getOriginalFilename();
System.out.println(fileName);
}
Problem is that when I require the file to be there (not having "required=false" after value="file") Then it can't find the suitable path for my request (404).
I have checked in browsers that there are a file sent to the server, with the name="file":(copy paste from chrome browser follows)
------WebKitFormBoundaryS7qP6QevHhFOyAZN
Content-Disposition: form-data; name="file"; filename="testfile"
Content-Type: application/octet-stream
------WebKitFormBoundaryS7qP6QevHhFOyAZN--
I really could use a hint here, can anyone help me?
Thanks in advance
Were missing the following in mappings:
servlet context.xml:
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
root-context.xml:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--25 mb max-->
<property name="maxUploadSize" value="26214400"/>
</bean>
and last In pom.xml (because i run maven project, else you need the jars)
<!-- Fileupload dependencies -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version> <!-- makesure correct version here -->
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>