Java : Cannot append an object (foreign key) to FormData object - java

i have an error in the frontend, the status code is 400.
i have no backend error.
i am trying to send a POST request to backend based on Spring Boot, while the frontend is an Angular 5 app.
i think the problem is the FormData object does not support object written in JSON. Am i right? if yes how to do?
i want to send a form that contain some input of type text, an input of type file, and an object(foreign key) of type PrestatairesTypes.
Here is the Entities :
#Entity
public class Prestataires implements Serializable
{
#Id #GeneratedValue
private Long id;
private String nom;
private String email;
private String tele;
private String fax;
private String rib;
private String adresse;
private String taches;
private String photo;
#Lob
private byte[] file;
#ManyToOne
#JoinColumn(name="ID_PRESTATAIRES_TYPES")
private PrestatairesTypes prestatairesTypes;
///Constructors and Getters and Setters
}
Here is the second Entity :
#Entity
public class PrestatairesTypes implements Serializable
{
#Id #GeneratedValue
private Long id;
private String designation;
//---------------------OneToMany---------------------
#OneToMany(mappedBy="prestatairesTypes")
private Collection<Prestataires> prestataires;
///Constructors and Getters and Setters
}
Here is the RestController :
#RestController
#CrossOrigin("*")
public class PrestatairesRestController
{
#Autowired
private PrestatairesRepository repository;
#RequestMapping(value="/prestataires",
method=RequestMethod.POST)
public Prestataires addVilles(Prestataires p,
#RequestParam("multipartFile") MultipartFile file)
{
byte[] rawFile = null;
try{
rawFile = file.getBytes();
}catch(Exception e){
e.printStackTrace();
}
p.setFile(rawFile);
return repository.save(p);
}
Here is the Prestataires Model :
export class PrestatairesModel
{
id:any;
nom:any;
email:any;
tele:any;
fax:any;
rib:any;
adresse:any;
taches:any;
photo:any;
file:any;
prestatairesTypes:any;
}
The PrestatairesTypes Model :
export class PrestatairesTypeModel
{
id:any;
designation:any;
}
The Service :
import {Injectable} from "#angular/core";
import {HttpClient, HttpEvent, HttpHeaders, HttpParams, HttpRequest} from
"#angular/common/http";
#Injectable()
export class PrestatairesService
{
host:string = "http://localhost:8080/";
constructor(private http:HttpClient)
{
}
uploadFile(model:any)
{
let formData = new FormData();
formData.append('multipartFile', model.file);
formData.append('nom', model.nom);
formData.append('email', model.email);
formData.append('rib', model.rib);
formData.append('taches', model.taches);
formData.append('fax', model.fax);
formData.append('adresse', model.adresse);
formData.append('tele', model.tele);
// when i remove this line it's work but i find null in the DataBase
formData.append('prestatairesTypes', model.prestatairesTypes);
let params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', this.host+"prestataires", formData,
options);
return this.http.request(req);
}
}
The Controller :
import { Component, OnInit } from '#angular/core';
import {PrestatairesService} from "../../services/prestataires.service";
import {PrestatairesTypeModel} from "../../modeles/prestatairesType.model";
import {PrestatairesModel} from "../../modeles/prestataires.model";
#Component({
selector: 'app-ajouter-prestataires',
templateUrl: './ajouter-prestataires.component.html',
styleUrls: ['./ajouter-prestataires.component.css']
})
export class AjouterPrestatairesComponent implements OnInit {
nom:any = null;
email:any = null;
tele:any = null;
fax:any = null;
rib:any = null;
adresse:any = null;
taches:any = null;
photo:any = null;
selectTypes:any;
typePrestataire:any;
tousLesPrestatairesTypes:any;
modelType:any;
imageURL:string = "../assets/images/MeG.jpg";
fileToUpload:File = null;
modelPrestataires:any;
constructor(private service:PrestatairesService) { }
ngOnInit()
{
this.getAllTypes();
}
handleFileInput(file:any)
{
this.fileToUpload = <File>file.target.files[0];
let reader = new FileReader();
reader.onload = (event:any)=>{
this.imageURL = event.target.result;
}
reader.readAsDataURL(this.fileToUpload);
}
getAllTypes()
{
this.service.getAllTypes()
.subscribe(data=>{
this.tousLesPrestatairesTypes = data;
}, err=>{
}, ()=>{
})
}
ajouterTypesPrestataires()
{
this.modelType = new PrestatairesTypeModel();
this.modelType.designation = this.typePrestataire;
this.service.ajouterType(this.modelType)
.subscribe(data=>{
this.getAllTypes();
this.modelType = data;
}, err=>{
}, ()=>{
})
}
ajouterPrestataires()
{
this.modelPrestataires = new PrestatairesModel();
this.modelPrestataires.nom = this.nom;
this.modelPrestataires.email = this.email;
this.modelPrestataires.tele = this.tele;
this.modelPrestataires.fax = this.fax;
this.modelPrestataires.rib = this.rib;
this.modelPrestataires.adresse = this.adresse;
this.modelPrestataires.taches = this.taches;
this.modelPrestataires.photo = this.photo;
this.modelPrestataires.file = this.fileToUpload;
this.service.getOneType(this.selectTypes)
.subscribe(data=>{
this.modelPrestataires.prestatairesTypes = data;
}, err=>{
}, ()=>{
this.service.uploadFile(this.modelPrestataires)
.subscribe(data=>{
this.modelPrestataires = data;
}, err=>{
}, ()=>{
});
});
}
getOneType(id:any)
{
this.service.getOneType(id)
.subscribe(data=>{
this.modelType = data;
}, err=>{
}, ()=>{
console.log("Complete");
});
}
}
The View :
<div class="right_col" role="main">
<div class="">
<div class="page-title">
<div class="title_left">
<h3>Ajouter Prestataires</h3>
</div>
</div>
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Nouveau Prestataire</h2>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"
role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
<ul class="dropdown-menu" role="menu">
<li><a routerLink="/prestataires">Retour Prestataires</a>
</li>
</ul>
</li>
<li><a class="close-link"><i class="fa fa-close"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div class="x_content">
<div id="containerAjouterPrestataires">
</div>
<form class="form-horizontal form-label-left"
enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Raison Social/Nom<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="nom" name="nom" type="text" required
class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Email<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="email" name="email" type="email"
required class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Téléphone<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="tele" name="tele" class="form-control
col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Fax<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="fax" name="fax" class="form-control
col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">RIB<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="rib" name="rib" class="form-control
col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Type<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<select class="form-control" name="selectTypes"
[(ngModel)]="selectTypes">
<option selected="selected" *ngFor="let s of
tousLesPrestatairesTypes" [value]="s.id" >
{{s.designation}}
</option>
</select>
<span class="input-group-btn">
<!-- Button trigger modal -->
<button type="button" class="btn btn-default" data-
toggle="modal" data-target="#myModal">
Ajouter Type
</button>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Adresse<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea [(ngModel)]="adresse" name="adresse"
class="form-control" rows="3" placeholder="Adresse"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Tâches<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea [(ngModel)]="taches" name="taches" class="form-
control" rows="3" placeholder="Tâches"></textarea>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-
dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Ajouter Type
Prestataire</h4>
</div>
<div class="modal-body">
<form class="form-horizontal form-label-left">
<div id="containerType">
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Nouveau Type<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="typePrestataire"
name="typePrestataire" class="form-control col-md-7 col-xs-12" type="text"
required>
</div>
<button type="button" class="btn btn-success"
(click)="ajouterTypesPrestataires()">Ajouter</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-
dismiss="modal" id="fermer">Fermer</button>
</div>
</div>
</div>
</div>
<!-- /modal -->
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Photo/Logo<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input name="multipartFile" class="form-control col-md-7
col-xs-12"
type="file" required="required"
(change)="handleFileInput($event)">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-
12">Image Preview</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<img class="imagePrestataires" [src]="imageURL">
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button class="btn btn-warning"
type="reset">Vider</button>
<button type="button" class="btn btn-success"
(click)="ajouterPrestataires()">Ajouter</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
please i need your help. it's a 4 days that i am blocked because of this error.

After a lot of testing, i found the solution.
i append only the id of the object PrestatairesTypes, and once at the backend i recover the full object by id and store it via Setter setPrestatairesTypes() and save the Object of type Prestataires. it's works Fine.

Related

Cannot send POST request via form while it's work with Postman

I have an error 400 at frontend based on Angular 5, no error at backend based on Spring-Boot. When i send request with Postman it's work correctly. I don't know what's the problem in my form.
Here is the Syndic entity :
package smart.syndic.entities;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
public class Syndic implements Serializable
{
#Id #GeneratedValue
private Long id;
private String numero;
private String nom;
private String email;
private String motPasse;
private String tele;
private String adresse;
private String honoraires;
private String nbrVote;
#Temporal(TemporalType.DATE)
private Date date1;
#Temporal(TemporalType.DATE)
private Date date2;
private String photo;
//-------------------Constructors--------------
//-------------------Getters and Setters-------
#ManyToOne
#JoinColumn(name="ID_SYNDIC_TYPES")
private SyndicTypes syndicTypes;
}
the second Entity SyndicTypes
package smart.syndic.entities;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
public class SyndicTypes implements Serializable
{
#Id #GeneratedValue
private Long id;
private String designation;
//------------------Constructors------------------
//------------------Getters and Setters------------------
#OneToMany(mappedBy="syndicTypes")
private Collection<Syndic> syndics;
}
The restcontroller :
package smart.syndic.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import smart.syndic.dao.SyndicRepository;
import smart.syndic.dao.SyndicTypesRepository;
import smart.syndic.entities.Syndic;
import smart.syndic.metier.StorageServiceSyndic;
#RestController
#CrossOrigin("*")
public class SyndicRestController
{
#Autowired
private SyndicRepository repository;
#Autowired
private StorageServiceSyndic storageServiceSyndic;
#Autowired
private SyndicTypesRepository repository2;
#RequestMapping(value="/syndic", method=RequestMethod.POST)
public Syndic addSyndic(Syndic s,
#RequestParam("file") MultipartFile file)
{
Syndic ss = null;
try
{
ss = repository.save(s);
storageServiceSyndic.store(file, "syndic", ss);
}
catch(Exception e)
{
e.printStackTrace();
//throw new RuntimeException("Impossible de stocker l'image");
}
s.setSyndicTypes(repository2.findOne(s.getSyndicTypes().getId()));
updateSyndic(s, s.getId());
return ss;
}
#RequestMapping(value="/syndic/{id}", method=RequestMethod.PUT)
public Syndic updateSyndic(
#RequestBody Syndic s,
#PathVariable Long id)
{
s.setId(id);
return repository.save(
}
The service in typescript :
import {Injectable} from "#angular/core";
import {HttpClient, HttpParams, HttpRequest} from "#angular/common/http";
#Injectable()
export class SyndicService
{
host:any = "http://localhost:8080/";
constructor(private http:HttpClient)
{
}
uploadFile(model:any)
{
let formData = new FormData();
formData.append('file', model.file);
formData.append('nom', model.nom);
formData.append('numero', model.numero);
formData.append('email', model.email);
formData.append('motPasse', model.motPasse);
formData.append('tele', model.tele);
formData.append('adresse', model.adresse);
formData.append('honoraires', model.honoraires);
formData.append('nbrVote', model.nbrVote);
formData.append('date1', model.date1);
formData.append('date2', model.date2);
formData.append('photo', model.photo);
formData.append('syndicTypes', model.selectTypeSyndic);
let params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', this.host+"syndic", formData, options);
return this.http.request(req);
}
}
The controller in typescript :
import { Component, OnInit } from '#angular/core';
import {SyndicService} from "../../services/syndic.service";
import {SyndicTypesModel} from "../../modeles/syndicTypes.model";
import {SyndicModel} from "../../modeles/syndic.model";
#Component({
selector: 'app-ajouter-syndic',
templateUrl: './ajouter-syndic.component.html',
styleUrls: ['./ajouter-syndic.component.css']
})
export class AjouterSyndicComponent implements OnInit {
selectTypeSyndic:any;
tousLesTypeSyndic:any;
numero:any;
nom:any;
email:any;
motPasse:any;
tele:any;
adresse:any;
honoraires:any;
nbrVote:any;
date1:any;
date2:any;
photo:any = null;
syndicTypes:any;
imageURL:any;
fileToUpload:any;
newType:any;
modelTypesSyndic:any;
modelSyndic:any;
constructor(private service:SyndicService) { }
ngOnInit() {
this.getAllTypes();
}
ajouterSyndic()
{
this.modelSyndic = new SyndicModel();
this.modelSyndic.numero = this.numero;
this.modelSyndic.nom = this.nom;
this.modelSyndic.email = this.email;
this.modelSyndic.motPasse = this.motPasse;
this.modelSyndic.tele = this.tele;
this.modelSyndic.adresse = this.adresse;
this.modelSyndic.honoraires = this.honoraires;
this.modelSyndic.nbrVote = this.nbrVote;
this.modelSyndic.date1 = this.date1;
this.modelSyndic.date2 = this.date2;
this.modelSyndic.file = this.fileToUpload;
this.modelSyndic.photo = this.photo;
this.modelSyndic.syndicTypes = this.selectTypeSyndic;
this.service.uploadFile(this.modelSyndic)
.subscribe(data=>{
this.modelSyndic = data;
}, err=>{
console.log(err);
}, ()=>{
});
}
}
The view in HTML :
<form class="form-horizontal form-label-left" #f1="ngForm"
enctype="multipart/form-data">
<div id="containerAjouterSyndic">
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Type de Syndic<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<select class="form-control"
name="selectTypeSyndic"
[(ngModel)]="selectTypeSyndic" >
<option *ngFor="let v of tousLesTypeSyndic"
[value]="v.id">
{{v.designation}}
</option>
</select>
<span class="input-group-btn">
<button type="button" class="btn btn-
default" data-toggle="modal" data-target="#myModalTypeSyndic">
Ajouter Type Syndic
</button>
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Numero<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="numero" name="numero"
class="form-control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Nom<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="nom" name="nom" class="form-
control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Email<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="email" name="email"
class="form-control col-md-7 col-xs-12" type="email" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Mot de Passe<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="motPasse" name="motPasse"
class="form-control col-md-7 col-xs-12" type="password" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Téléphone<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="tele" name="tele" class="form-
control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Adresse<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea [(ngModel)]="adresse" name="adresse"
class="form-control" placeholder="Adresse...">
</textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Honoraires<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="honoraires" name="honoraires"
class="form-control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Nombre Vote<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="nbrVote" name="nbrVote"
class="form-control col-md-7 col-xs-12" type="text" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Date Début Mondat<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="date1" name="date1"
type="date" class="form-control col-md-7 col-xs-12" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Date Fin Mondat<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="date2" name="date2"
type="date" class="form-control col-md-7 col-xs-12" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Photo<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input name="file" class="form-control col-sm-6
col-md-7 col-xs-12"
type="file" required
(change)="handleFileInput($event)">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Image Preview</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<img class="imagePrestataires" [src]="imageURL">
</div>
</div>
</form>
<!-- Modal Type -->
<div class="modal fade" id="myModalTypeSyndic" tabindex="-1"
role="dialog" aria-labelledby="myModalLabelType">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabelType">Ajouter
Type Syndic</h4>
</div>
<div class="modal-body">
<form class="form-horizontal form-label-left"
enctype="multipart/form-data">
<div id="containerTypeSyndic">
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-
xs-12">Nouveau Type<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input [(ngModel)]="newType" name="newType"
class="form-control col-md-7 col-xs-12" type="text" required>
</div>
<button type="button" class="btn btn-success"
(click)="ajouterTypes()">Ajouter</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-
dismiss="modal">Fermer </button>
</div>
</div>
</div>
</div>
<!-- / Modal Options -->
<div class="ln_solid">
</div>
</div>
</div>
The code generated by Postman that work :
POST /syndic HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
Postman-Token: 568c8846-87a6-c194-2845-bdb6a6da1e69
Content-Type: multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="numero"
sdsd
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="nom"
sdsd
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="email"
sdsd
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="motPasse"
sdsd
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="tele"
sdsd
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="adresse"
sdsd
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="honoraires"
dsdsd
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="nbrVote"
adfg
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="date1"
01/01/1990
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="date2"
01/01/2009
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file";
filename="39320551_2003684179922600_4018500942646214656_n.jpg"
Content-Type: image/jpeg
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="photo"
null
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="syndicTypes"
1
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Thanks.
On your dates fields you must give a format for each date, for example:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm")
private Date date1;

Dropdown menu for editing categories doesn't work

I'm making a simple blog using springframework. I'm trying to make Categories for my posts/articles. When I create articles, I have the option to choose a Category and it works fine. However, when I try to edit an Article, the drop-down menu for choosing a Category is not working. It's just and empty field with a 'down arrow' sidebad and nothing happens when I click on it
//ARTICLE EDIT--------------------------------------------------
#GetMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String edit(#PathVariable Integer id, Model model)
{
if(!this.articleRepository.exists(id))
{
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!isUserAuthorOrAdmin(article))
{
return "redirect:/article/"+id;
}
List<Category> categories = this.categoryRepository.findAll();
String tagString = article.getTags().stream().map(Tag::getName).collect(Collectors.joining(", "));
model.addAttribute("view", "article/edit");
model.addAttribute("article", article);
model.addAttribute("category", categories);
model.addAttribute("tags", tagString);
return "base-layout";
}
#PostMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String editProcess(#PathVariable Integer id, ArticleBindingModel articleBindingModel)
{
if(!this.articleRepository.exists(id))
{
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
Category category = this.categoryRepository.findOne(articleBindingModel.getCategoryId());
HashSet<Tag> tags = this.findTagsFromString(articleBindingModel.getTagString());
if(!isUserAuthorOrAdmin(article))
{
return "redirect:/article/"+id;
}
article.setContent(articleBindingModel.getContent());
article.setTitle(articleBindingModel.getTitle());
article.setCategory(category);
article.setTags(tags);
this.articleRepository.saveAndFlush(article);
return "redirect:/article/" + article.getId();
}
The html file is:
<main>
<div class="container body-content span=8 offset=2">
<div class="well">
<form class="form-horizontal" th:action="#{/article/edit/{id}(id=${article.id})}" method="POST">
<fieldset>
<legend>Edit Post</legend>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_title">Post Title</label>
<div class="col-sm-4 ">
<input type="text" class="form-control" id="article_title" placeholder="Post Title" name="title" th:value="${article.title}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_content">Content</label>
<div class="col-sm-6">
<textarea class="form-control" rows="6" id="article_content" name="content" th:field="${article.content}"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_tags">Tags</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="article_tags" placeholder="Tags" name="tagString" th:value="${tags}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="article_category">Category</label>
<div class="col-sm-6">
<select class="form-control" id="article_category" name="categoryId">
<option th:each="category : ${categories}" th:value="${category.id}" th:text="${category.name}" th:selected="${category.id == article.category.id}">
</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-4">
<a class="btn btn-default" th:href="#{/article/{id}(id = ${article.id})}">Cancel</a>
<input type="submit" class="btn btn-success" value="Edit"/>
</div>
</div>
</fieldset>
</form>
</div>
</div>
You should use model attributes' names inside ${}. There is a mismatch between model.addAttribute("category", categories); and th:each="category : ${categories}".
Change model attribute name to "categories" and it should be fine
model.addAttribute("categories", categories);

HTTP Status 400 - The request sent by the client was syntactically incorrect. Spring / $.ajax()

This is my Controller:
package br.com.apptrechos.torcidapremiada.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties.User;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import br.com.apptrechos.torcidapremiada.model.Beneficio;
import br.com.apptrechos.torcidapremiada.model.Imovel;
import br.com.apptrechos.torcidapremiada.model.Partida;
import br.com.apptrechos.torcidapremiada.repository.Imoveis;
import br.com.apptrechos.torcidapremiada.repository.Partidas;
import br.com.apptrechos.torcidapremiada.service.BeneficioService;
import br.com.apptrechos.torcidapremiada.service.exception.DadoJaCadastradoException;
#Controller
#RequestMapping("/beneficio")
public class BeneficioController {
#Autowired
private Partidas partidas;
#Autowired
private Imoveis imoveis;
#Autowired
private BeneficioService beneficioService;
#PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<?> validarBeneficio(#RequestBody Long codigo, #AuthenticationPrincipal User user) {
try {
Imovel imovel = this.imoveis.findByCodigoIn(codigo);
Partida proximaPartida = this.partidas.buscarProximaPartida();
Beneficio beneficio = new Beneficio(proximaPartida, user.getName(), imovel, imovel.getContribuinte());
this.beneficioService.salvar(beneficio);
} catch (DadoJaCadastradoException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
return ResponseEntity.ok().build();
}
}
My Javascript and my view:
var TorcidaPremiada = TorcidaPremiada || {};
TorcidaPremiada.ImovelConcederBeneficio = (function() {
function ImovelConcederBeneficio() {
this.validaBeneficioBtn = $('.js-valida-beneficio-btn');
this.containerMensagemErro = $('.js-container-mensagem-erro');
this.containerMensagemSucesso = $('.js-container-mensagem-sucesso');
}
ImovelConcederBeneficio.prototype.iniciar = function() {
this.validaBeneficioBtn.on('click', onBotaoValidaBeneficioClick.bind(this));
}
function onBotaoValidaBeneficioClick(event) {
var botao = $(event.currentTarget);
var codigo = botao.data('codigo');
var url = botao.data('url');
$.ajax({
url: url,
method: 'POST',
data: JSON.stringify({codigo: codigo}),
contentType: 'application/json',
success: onSuccess.bind(this),
error: onError.bind(this)
});
}
function onSuccess() {
var mensagem = 'Benefício concedido com sucesso!';
this.containerMensagemSucesso.removeClass('hidden');
this.containerMensagemSucesso.html('<span>' + mensagem + '</span>');
}
function onError(object) {
console.log(error);
var mensagem = object.responseText;
this.containerMensagemErro.removeClass('hidden');
this.containerMensagemErro.html('<i class="fa fa-exclamation-circle"></i><span> ' + mensagem + '</span>');
}
return ImovelConcederBeneficio;
}());
$(function() {
var imovelConcederBeneficio = new TorcidaPremiada.ImovelConcederBeneficio();
imovelConcederBeneficio.iniciar();
});
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org"
xmlns:tp="http://www.apptrechos.com.br"
xmlns:data="http://www.thymeleaf.org/extras/data"
layout:decorate="~{layout/layout-padrao}">
<head>
<title>Torcida Premiada - Cadastro de Imóveis</title>
<link rel="stylesheet" type="text/css" th:href="#{/stylesheets/vendors/bootstrap-switch.min.css}" />
</head>
<section layout:fragment="conteudo">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2 th:if="${imovel.novo}">Cadastro de Imóveis</h2>
<h2 th:unless="${imovel.novo}">Edição de Imóvel</h2>
<ul class="nav navbar-right panel_toolbox">
<li>
<a th:href="#{/imovel}"><i class="fa fa-search"></i> <span>Pesquisa de Imóveis</span></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
<form method="POST" class="form-horizontal form-label-left" th:object="${imovel}" th:action="#{/imovel/novo}">
<tp:message />
<div class="alert alert-danger alert-dismissible fade in hidden js-container-mensagem-erro" role="alert"></div>
<div class="alert alert-success alert-dismissible fade in hidden js-container-mensagem-sucesso" role="alert"></div>
<input type="hidden" th:field="*{codigo}" />
<div class="form-group tp-required" tp:classforerror="inscricaoImobiliaria">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="inscricaoImobiliaria">Inscrição Imobiliária</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="inscricaoImobiliaria" maxlength="16" class="form-control col-md-7 col-xs-12 input-imobiliario" th:readonly="${not imovel.novo}" th:field="*{inscricaoImobiliaria}" />
</div>
</div>
<div class="form-group tp-required" tp:classforerror="contribuinte.codigo">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nomeContribuinte">Contribuinte</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="input-group">
<input type="text" id="nomeContribuinte" class="form-control" readonly="readonly" th:field="*{contribuinte.nome}"
placeholder="Clique na lupa para pesquisar o contribuinte" />
<input type="hidden" id="codigoContribuinte" th:field="*{contribuinte}" />
<span class="input-group-btn">
<button type="button" class="btn btn-default js-tooltip" title="Pesquisar"
data-toggle="modal" data-target="#pesquisaRapidaDeContribuintes" th:disabled="${not imovel.novo}">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
</div>
<div class="form-group tp-required" tp:classforerror="condicaoDeResidente">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="condicaoDeResidente">Condição de Residente</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select id="condicaoDeResidente" class="select2_single form-control" tabindex="-1" th:field="*{condicaoDeResidente}">
<option value="">Selecione uma condição</option>
<option th:each="condicaoDeResidente : ${condicoesDeResidencia}" th:value="${condicaoDeResidente}" th:text="${condicaoDeResidente.descricao}"></option>
</select>
</div>
</div>
<div class="form-group tp-required" tp:classforerror="situacao">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="situacao">Situação</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select id="situacao" class="select2_single form-control" tabindex="-1" th:field="*{situacao}">
<option value="">Selecione uma situação</option>
<option th:each="situacao : ${situacoes}" th:value="${situacao}" th:text="${situacao.descricao}"></option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Status</label>
<div class="col-md-4 col-sm-4 col-xs-6">
<input type="checkbox" class="js-status" data-size="small"
data-on-color="primary" data-off-color="danger"
data-on-text="Ativo" data-off-text="Inativo"
data-inverse=true th:field="*{status}" />
</div>
<div class="col-md-5 col-sm-5 col-xs-6" th:unless="${imovel.novo}">
<button type="button" class="btn btn-success btn-sm js-valida-beneficio-btn" data:codigo="${imovel.codigo}" data:url="#{/beneficio}">Validar Benefício</button>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button type="submit" class="btn btn-primary js-cancelar-btn">Cancelar</button>
<button type="submit" class="btn btn-success">Salvar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<th:block th:replace="pesquisa-rapida/pesquisa-rapida-de-contribuintes :: pesquisaRapidaDeContribuintes"></th:block>
</section>
<th:block layout:fragment="javascript-extra">
<script th:src="#{/javascripts/vendors/handlebars.min.js}"></script>
<script th:src="#{/javascripts/contribuinte.pesquisa-rapida.js}"></script>
<script th:src="#{/javascripts/vendors/bootstrap-switch.min.js}"></script>
<script th:src="#{/javascripts/imovel.condeder-beneficio.js}"></script>
<script>
$(".js-status").bootstrapSwitch();
</script>
</th:block>
</html>
When I click on the button, the ajax request doesn't reach to the controller. The browser console shows error HTTP Status 400 - The request sent by the client was syntactically incorrect.
The followings are the request data.
Would anybody help me?

Receiving 400 bad request when sending a POST with Angularjs (datepicker component)

My web app is basically: jsp + angularjs, but this datepicker is running with jQuery because of the template I am using.
Before explaining what is happening, my DTO's attributes matches my entity attributes, both java.util.Date, I am just informing that I already verified the attributes type because I got many 400 bad requests because of that.
I have a modal where I have many fields, but I inserted recently two datepickers (bootstrap) and till then app is crashing, when I send the POST via ajax to my java controller, I am receiving a bad request (400), I think that it is because the format is wrong (mm/dd/yyyy). I formatted correctly the date to pt_BR for Brazil but it is not working.
BoxApp.controller("UsuariosController", function($scope, $http) {
$scope.usuarios={};
$scope.usuariosParaAlterar={};
$scope.iniciar = function() {
$http.get('/boxmlV2/usuario').success(function (response) {
$scope.usuarios = response;
});
};
$scope.iniciar();
$scope.setSelected = function(selecao){
$scope.usuariosParaAlterar = selecao;
};
/**
* Trecho para validar o form ao submeter.
*/
$scope.submitted = false;
$scope.submitForm = function(formUsuarios) {
$scope.submitted = true;
if (formUsuarios.$valid) {
$("#dataValidadeConta").datepicker({
format: 'dd/mm/yyyy',
language: 'pt-BR'
});
$("#dataValidadeSenha").datepicker({
format: 'dd/mm/yyyy',
language: 'pt-BR'
});
$scope.editaUsuario();
}
};
$scope.editaUsuario = function() {
$http.post('/boxmlV2/usuario/salvarUsuario', {
ativo : $scope.usuariosParaAlterar.ativo,
idUsuario : idUsuario.value,
nome : nome.value,
senha : senha.value,
email : email.value,
bloqueado : $scope.usuariosParaAlterar.bloqueado,
dataValidadeConta : $scope.usuariosParaAlterar.dataValidadeConta,
dataValidadeSenha : $scope.usuariosParaAlterar.dataValidadeSenha,
resetSenha : $scope.usuariosParaAlterar.resetSenha,
perfil : $scope.usuariosParaAlterar.perfil
}).then(function(response) {
$scope.sucesso();
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
$scope.sucesso = function() {
$scope.closeMyPopup();
$scope.iniciar();
};
$scope.closeMyPopup = function() {
$(myModal_autocomplete).modal('hide');
};
$scope.preparaInsercao = function() {
nome.value = "";
senha.value = "";
email.value = "";
$(idUsuario).val("");
$(idUsuario).hide();
$(idLabel).hide();
};
});
<!-- START MODAL -->
<div id="myModal_autocomplete" class="modal fade" role="dialog"
aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true"></button>
<h4 class="modal-title">Cadastro de Usuário</h4>
</div>
<div class="modal-body form">
<form name="form" id="form_sample_2" role="form"
class="form-horizontal ng-pristine ng-valid" novalidate>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Ativo:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="ativo"
ng-model="usuariosParaAlterar.ativo" value="true">
Sim <br />
</label> <label class="btn btn-default"> <input
type="radio" name="ativo"
ng-model="usuariosParaAlterar.ativo" value="false">
Não <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Nome:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="text" ng-model="usuariosParaAlterar.nome"
class="form-control" id="nome" maxlength="100" name="nome"
required> <span style="color: red"
ng-show="submitted && form.nome.$error.required">Campo
Nome Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Senha:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="password" ng-model="usuariosParaAlterar.senha"
class="form-control" maxlength="100" name="senha"
placeholder="Do E-mail De Recebimento do XML" id="senha"
required> <span style="color: red"
ng-show="submitted && form.senha.$error.required">Campo
Senha Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">E-mail:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="email" ng-model="usuariosParaAlterar.email"
class="form-control" id="email" maxlength="100"
name="email" required> <span style="color: red"
ng-show="submitted && form.email.$error.required">Campo
E-mail Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Bloqueado:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="bloqueado"
ng-model="usuariosParaAlterar.bloqueado" value="true">
Sim <br />
</label> <label class="btn btn-default"> <input
type="radio" name="bloqueado"
ng-model="usuariosParaAlterar.bloqueado" value="false">
Não <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Data Validade Conta:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input
class="form-control form-control-inline input-medium date-picker"
name="dataValidadeConta" id="dataValidadeConta"
ng-model="usuariosParaAlterar.dataValidadeConta"
size="16" type="text" value="" required/> <span
class="help-block"> Selecione a data </span>
<span style="color: red"
ng-show="submitted && form.dataValidadeConta.$error.required">Campo
Data Validade Conta Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Data Validade Senha:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input
class="form-control form-control-inline input-medium date-picker"
ng-model="usuariosParaAlterar.dataValidadeSenha"
name="dataValidadeSenha" id="dataValidadeSenha"
size="16" type="text" value="" required/> <span
class="help-block"> Selecione a data </span>
<span style="color: red"
ng-show="submitted && form.dataValidadeSenha.$error.required">Campo
Data Validade Senha Obrigatório.</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Resetar Senha:<span
class="required" aria-required="true"> * </span>
</label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="resetSenha"
ng-model="usuariosParaAlterar.resetSenha" value="true">
Sim <br />
</label> <label class="btn btn-default"> <input
type="radio" name="resetSenha"
ng-model="usuariosParaAlterar.resetSenha" value="false">
Não <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Perfil
Usuário:<span class="required" aria-required="true">
* </span>
</label>
<div class="col-md-9">
<div class="clearfix">
<div>
<label class="btn btn-default active"> <input
type="radio" name="perfil"
ng-model="usuariosParaAlterar.perfil" value="true">
Admin <br />
</label> <label class="btn btn-default"> <input
type="radio" name="perfil"
ng-model="usuariosParaAlterar.perfil" value="false">
Usuário <br />
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label id="idLabel" class="control-label col-md-3">ID:<span
class="required" aria-required="true"> * </span></label>
<div class="col-md-9">
<input type="text" ng-model="usuariosParaAlterar.idUsuario"
class="form-control" id="idUsuario" maxlength="100"
name="idUsuario" required disabled> <span
style="color: red"
ng-show="submitted && form.idUsuario.$error.required">Campo
ID Obrigatório.</span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary"
ng-click="submitForm(form)">
<i class="fa fa-check"></i> Salvar
</button>
</div>
</div>
</div>
</div>
<!-- END MODAL -->
Controller:
package br.com.kolss.boxml.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import br.com.kolss.boxml.dto.RetornoDTO;
import br.com.kolss.boxml.dto.UsuarioDTO;
import br.com.kolss.boxml.enums.RetornoEnum;
import br.com.kolss.boxml.service.UsuarioService;
#Controller
public class CadastroUsuariosController {
#Autowired
private UsuarioService usuarioService;
#RequestMapping(value="/usuario", method=RequestMethod.GET)
public ModelAndView iniciar(ModelMap modelMap){
return new ModelAndView("usuario");
}
#RequestMapping(value="/usuario",method=RequestMethod.GET,produces={"application/json"})
public #ResponseBody List<UsuarioDTO> obterTodos(ModelMap modelMap){
return usuarioService.obterTodos();
}
#RequestMapping(value = "/usuario/salvarUsuario", method = RequestMethod.POST, produces = { "application/json" })
public #ResponseBody RetornoDTO insereOuEditaUsuario(
#RequestBody UsuarioDTO usuarioDTO) {
usuarioService.insereOuEditaUsuario(usuarioDTO);
return new RetornoDTO(RetornoEnum.SUCESSO);
}
}
The date formatting to pt_BR only applies to how it is displayed in the datepicker control. Note that you are sending back a string mm/dd/yyyy to the server, you need to be sure that it is parsed as such at the controller.

File uploading not working in spring mvc using spring form

I have a jsp page in which i have used spring form tag so that i can use model attribute and bind data to it. It was working fine on submit the form but after adding enctype="multipart/form-data" model attributes are returing null to the controller. What is wrong here ?
My Code is -
proflie.jsp
<sf:form method="POST" action="update" modelAttribute="user" class="form-horizontal" >
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Avatar</label>
<div class="col-md-6">
<div class="media v-middle">
<div class="media-left">
<div class="icon-block width-100 bg-grey-100">
<i class="fa fa-photo text-light"></i>
</div>
</div>
<div class="media-body">
<i class="fa fa-upl"><sf:input path="imageFile" type="file" class="btn btn-white btn-sm paper-shadow relative" placeholder="Add Image" id="imageFile" />
</i>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Full Name</label>
<div class="col-md-8">
<div class="row">
<div class="col-md-6">
<div class="form-control-material">
<sf:input path="firstName" type="text" class="form-control" id="firstName" placeholder="Your first name" value="${user.firstName}" />
<sf:input path="id" type="hidden" class="form-control" id="id" value="${user.id}" />
<label for="firstName">First name</label>
</div>
</div>
<div class="col-md-6">
<div class="form-control-material">
<sf:input path="lastName" class="form-control" id="lastName" placeholder="Your last name" value="${user.lastName}" />
<label for="lastName">Last name</label>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Email</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<sf:input path="email" type="email" class="form-control" id="inputEmail3" placeholder="Email" value="${user.email}" />
<label for="inputEmail3">Email address</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Phone</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<sf:input path="phone" type="number" class="form-control" id="inputEmail3" placeholder="Phone" value="${user.phone}" />
<label for="phone">Phone</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-md-2 control-label">Address</label>
<div class="col-md-6">
<div class="form-control-material">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-link"></i></span>
<sf:input path="address" type="text" class="form-control used" id="website" placeholder="Address" value="${user.address}" />
<label for="address">Address</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-md-2 control-label">Change Password</label>
<div class="col-md-6">
<div class="form-control-material">
<sf:input path="password" type="password" class="form-control" id="inputPassword3" placeholder="Password" value="${user.password}" />
<label for="password">Password</label>
</div>
</div>
</div>
<div class="form-group margin-none">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated>Save Changes</button>
</div>
</div>
</sf:form>
AccountController class
package com.vc.teacher.controller;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.vc.teacher.db.dao.UserDao;
import com.vc.teacher.entities.User;
import com.vc.teacher.util.Constants;
#Controller
public class AccountController {
#Autowired
UserDao userDao;
#RequestMapping("/login")
public String loginUser(#RequestParam("email") String email,
#RequestParam("password") String password, Model model) {
User user = userDao.checkCreditionals(email, password);
if (user != null) {
model.addAttribute("user", user);
return "jsp/profile";
} else {
model.addAttribute("error", "Wrong creditionals");
return "jsp/signin";
}
}
#RequestMapping("/signUp")
public String initilize(Model model) {
model.addAttribute(new User());
return "jsp/signup";
}
#RequestMapping(method = RequestMethod.POST, value = "/register")
public String signUpUser(User user, RedirectAttributes attributes) {
boolean result = false;
File imageFile = null;
try {
imageFile = user.getImageFile();
if (imageFile != null) {
File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
FileUtils.copyFile(imageFile, imageFileSave);
user.setImageFileName(imageFile.getName());
}
user.setStatus("Deactive");
result = userDao.registerUser(user);
if (result == true) {
attributes.addFlashAttribute("message",
"You are ready to go now !");
return "redirect:/signUp";
} else {
attributes.addFlashAttribute("message", "Something went wrong");
return "redirect:/signUp";
}
} catch (Exception e) {
attributes.addFlashAttribute("message", "Something went wrong");
return "redirect:/signUp";
}
}
#RequestMapping(method = RequestMethod.POST, value = "/update")
public String updateUser(User user, RedirectAttributes attributes) {
boolean result = false;
File imageFile = null;
try {
System.out.println("=================================="+user.getEmail());
System.out.println("=================================="+user.getId());
System.out.println("=================================="+user.getFirstName());
imageFile = user.getImageFile();
if (imageFile != null) {
File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
FileUtils.copyFile(imageFile, imageFileSave);
user.setImageFileName(imageFile.getName());
}
user.setStatus("Active");
result = userDao.updateUser(user);
if (result == true) {
attributes.addFlashAttribute("message", "Profile Updated !");
return "jsp/profile";
} else {
attributes.addFlashAttribute("message", "Something went wrong");
return "jsp/profile";
}
} catch (Exception e) {
attributes.addFlashAttribute("message", "Something went wrong");
return "jsp/profile";
}
}
}
On its own, DispatcherServlet doesn't know how to handle multipart form data; that's why we require multipart resolver.
You should register it in your servlet-config:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="500000" />
</bean>
Use CommonsMultipartFile or MultipartFile instead of File in your User object:
private CommonsMultipartFile imageFile;
You can try this code to save file:
File imageFileSave = new File(Constants.MEDIA_FILE_PATH);
FileUtils.writeByteArrayToFile(imageFileSave , imageFile.getBytes());

Categories

Resources