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.
Related
I am working with Java ArrayList and thymeleaf. I need to use the list in thymeleaf for adding value dynamically. I don't understand how to do that?
Model
public class MedicineDTO {
private Long brandId;
private Long stockId;
private double quantity;
private double discount;
private double total;
}
public class InvoiceDTO {
private String customerName;
private String mobileNumber;
private List<MedicineDTO> medicineDTOList;
private double averageDiscount;
private double totalDiscount;
private double grandTotal;
}
Controller
#RequestMapping(value = "/pos")
public String getPOS(Model model) {
List<Brand> brandList = brandService.getAllBrands();
List<MedicineDTO> medicineDTOList = new ArrayList<>();
InvoiceDTO invoiceDTO = new InvoiceDTO();
invoiceDTO.setMedicineDTOList(medicineDTOList);
model.addAttribute("medicinedto", new MedicineDTO());
model.addAttribute("invoicedto", invoiceDTO);
model.addAttribute("brands", brandList);
return "pos";
}
#PostMapping(value="/pos/payment")
public String makePayment(InvoiceDTO invoiceDTO){
System.out.println(invoiceDTO);
service.makePayment(invoiceDTO);
return "invoice/invoice";
}
pos.html
<form id="posForm" th:action="#{/pos/payment}" th:object="${invoicedto}" method="post">
<div class="card-body">
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="name">Customer Name</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="name"
th:field="*{customerName}"
placeholder="Enter Customer Name">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label" for="mobile">Mobile No</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="mobile"
th:field="*{mobileNumber}"
placeholder="Enter Mobile Number">
</div>
</div>
<div class="col-sm-4 col-md-2">
<button type="button" class="btn btn-success btn-sm add-row">
Add
</button>
<button type="reset" class="btn btn-primary btn-sm">
Reset
</button>
</div>
<table class="table" id="brand_tbl">
<thead>
<tr>
<th>Brand Name</th>
<th>Expired Date</th>
<th>Stock</th>
<th>Quantity</th>
<th>Price</th>
<th>Discount %</th>
<th>Total</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr th:object="${medicinedto}">
<td>
<select id="selectBrand1" class="form-control select2"
th:field="*{brandId}"
onchange="changeBrand(this);"
style="width: 100%;">
<option value=""> --</option>
<option th:each="brand : ${brands}"
th:value="${brand.id}"
th:utext="${brand.name}">
</select>
</td>
<td style="width:15%">
<select id="selectDate1" class="form-control select2"
onchange="changeDate(this);"
style="width: 100%;">
<option value=""> --</option>
</select>
</td>
<td style="width:10%">
<input type="number" class="form-control" id="stock1"
placeholder="" disabled>
<input type="hidden" id="stockId1" th:field="*{stockId}">
</td>
<td style="width:10%">
<input type="number" class="form-control" id="quantity1"
th:field="*{quantity}"
onchange="changeQuantity(this);"
placeholder="">
</td>
<td style="width:12%">
<input type="number" class="form-control" id="price1"
placeholder="" disabled>
</td>
<td style="width:12%">
<input type="number" class="form-control" id="discount1"
onchange="changeDiscount(this);"
placeholder="0">
<input type="hidden" id="discountAmount1" th:field="*{discount}">
</td>
<td style="width:12%">
<input type="number" class="form-control" id="total1"
th:field="*{discount}"
placeholder="" readonly>
</td>
<td>
<button type="button"
class="btn btn-block btn-danger btn-sm delete-row">
Delete
</button>
</td>
<div th:text="${invoicedto.medicineDTOList.add(medicinedto)}" th:remove="all"></div>
</tr>
</tbody>
</table>
</br>
</br>
</br>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="average_discount">
Average Discount
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="average_discount"
th:field="*{averageDiscount}"
onchange="changeAverageDiscount();">
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label justify-content-end" for="total_discount">
Total Discount
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="total_discount"
th:field="*{totalDiscount}"
readonly>
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="vat">
Vat
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="vat" disabled>
</div>
<div class="col-sm-1">
<input type="checkbox" id="vat_checkbox" name="vat_checkbox">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="tax">
Tax
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="tax" disabled>
</div>
<div class="col-sm-1">
<input type="checkbox" id="tax_checkbox" name="tax_checkbox">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="total_tax">
Total Tax
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="total_tax" disabled>
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="grand_total">
Grand Total
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="grand_total"
th:field="*{grandTotal}"
readonly>
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="paid_amount">
Paid Amount
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="paid_amount"
onchange="changePaidAmount();">
</div>
<div class="col-sm-1">
</div>
</div>
<div class="form-group row justify-content-end">
<label class="col-sm-2 col-form-label" for="change">
Change
</label>
<div class="col-sm-2">
<input type="number" class="form-control" id="change" disabled>
</div>
<div class="col-sm-1">
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
I am trying to add list value in thymeleaf frontend this way. I am passing two object from controller to html. And i am using <div th:text="${invoicedto.medicineDTOList.add(medicinedto)}" th:remove="all"></div> for adding medicindto object. But It passes null list to controller. Do you have any idea how i solve my problem? thanks in advance.
Thymeleaf is used to process HTML templates, add data to it, do some checks such as th:if, th:unless and also loops through an array of objects using th:each etc. But all of this is done on the server side. Once the HTML template has been delivered to the client (the browser in this case), thymeleaf is not applicable there.
So on the client side, you have to rely on HTML and JavaScript to get everything done, including preparing your data to be submitted in the form.
Based on the explanation above, you can do some more research on how to handle list on html forms. I found this solution to be appropriate for your use case, you can study it and use it.
He has used Ratings[' + rating + '][Value] in his solution, you will use something like medicineDTOList[' + index + '][brandId]. Why medicineDTOList? because in InvoiceDto which is your form's th:object, the list of MedicineDto is called medicineDTOList.
The [index] refers to the array index, which will correspond to the position of the MedicineDto in your arraylist and [brandId] correspond to the property of the MedicineDto at that index.
Upon submitting the form, java will parse the form's data into your "DTO" which is InvoiceDTO.
Here I have a form that accepts package details and I have added dynamic form fields to get all the itineraries of that package. Please comment on what I must add to my question to make it more clear.
insert function
#PostMapping("/save-tour-package")
public String saveTourPackage(#ModelAttribute("tourPackage") TourPackage tourPackage, #RequestParam String[] day, #RequestParam String[] itinerary_title, #RequestParam String[] itinerary_description, #RequestParam String[] itinerary_altitude) {
// save package to database
TourPackage tour = tourPackageService.saveTourPackage(tourPackage);
for (int i = 0; i < day.length; i++) {
Itinerary ite = new Itinerary();
ite.setPackages(tour);
ite.setDay(day[i]);
ite.setTitle(itinerary_title[i]);
ite.setDescription(itinerary_description[i]);
ite.setAltitude(itinerary_altitude[i]);
itineraryRepo.save(ite);
}
return "redirect:/";
}
save service implementation
#Override
public TourPackage saveTourPackage(TourPackage tourPackage) {
return this.tourPackagesRepo.save(tourPackage);
}
view file
<div layout:fragment="content">
<div class="container">
<form th:action="#{/save-tour-package}" th:object="${tourPackage}" method="POST">
<div class="form-group">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" th:field="*{title}" placeholder="Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" th:field="*{description}"
placeholder="Description"></textarea>
</div>
<div class="row">
<div class="col-3">
<div class="form-group">
<label for="geography">Geography</label>
<input type="text" class="form-control" id="geography" th:field="*{geography}"
placeholder="Geography">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" id="location" th:field="*{location}"
placeholder="Location">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="difficulty">Difficulty</label>
<input type="text" class="form-control" id="difficulty" th:field="*{difficulty}"
placeholder="Difficulty">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="altitude">Altitude</label>
<input type="text" class="form-control" id="altitude" th:field="*{altitude}"
placeholder="Altitude">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="religion">Religion</label>
<input type="text" class="form-control" id="religion" th:field="*{religion}"
placeholder="Title">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="ethnic_people">Ethnic People</label>
<input type="text" class="form-control" id="ethnic_people" th:field="*{ethnic_people}"
placeholder="Ethnic People">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="accommodation">Accommodation</label>
<input type="text" class="form-control" id="accommodation" th:field="*{accommodation}"
placeholder="Title">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="transportation">Transportation</label>
<input type="text" class="form-control" id="transportation" th:field="*{transportation}"
placeholder="Transportation">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="minimum_pax">Minimum Pax</label>
<input type="text" class="form-control" id="minimum_pax" th:field="*{minimum_pax}"
placeholder="Minimum Pax">
</div>
</div>
<div class="col-3">
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price" th:field="*{price}" placeholder="Price">
</div>
</div>
</div>
<div class="row">
<div class="col-2">Day</div>
<div class="col-3">Title</div>
<div class="col-3">Description</div>
<div class="col-3">Altitude</div>
<div class="col-1"></div>
</div>
<div class="row delete-field append-new-field">
<div class="col-2">
<input type="text" class="form-control" name="day">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_title">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_description">
</div>
<div class="col-3">
<input type="text" class="form-control" name="itinerary_altitude">
</div>
<div class="col-1">
<i class="fas fa-minus-circle"></i>
</div>
</div>
Add Fields
<div class="form-group">
<button type="submit" class="btn btn-info col-2"> Save Tour Package</button>
</div>
</div>
</form>
</div>
</div>
<div layout:fragment="after-script">
<script>
function addItineraryFields() {
var html = '<div class="row delete-field"><div class="col-2">\n' +
' <input type="text" class="form-control" name="day">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_title">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_description">\n' +
' </div>\n' +
' <div class="col-3">\n' +
' <input type="text" class="form-control" name="itinerary_altitude">\n' +
' </div>' +
' <div class="col-1">\n' +
' <i class="fas fa-minus-circle"></i>\n' +
' </div></div>';
$('.append-new-field').append(html);
}
$(document).on('click', '.delete-row', function(e) {
$(this).closest('.delete-field').remove();
return false;
});
</script>
</div>
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.
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?
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());