Springframework - property or field cannot be found on null - java

I am working on a project and keep getting an error.
<span style="font-style: italic;" th:text="${user != null} ? ${#strings.toUpperCase(user.username)} : 'user is null'"></span>
EL1007E: Property or field 'id' cannot be found on null
I'm new to thyemeleaf and spring so still learning so not sure what you would need to help figure out the issue so I will update when I know what I need to provide.
Header HTML where login/New user modal is
<body>
<div th:fragment="navbar">
<div class="container">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<a class="navbar-brand active" href="https://inplaydesign.com/index.html">d|b</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="https://blog.inplaydesign.com">blog</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/gallery/gallery.html">gallery</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">shop</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/faq/faq.html">f.a.q.</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/contact/contact.html">contact</a>
</li>
</ul>
<button type="button" class="btn btn-outline-dark">
<i class="fa fa-shopping-cart"></i> Shopping Cart
</button>
<button sec:authorize="isAnonymous()" type="button" class="btn btn-outline-dark" data-toggle="modal" data-target="#accountAccess">
<i class="fa fa-id-card"></i> Account
</button>
<a sec:authorize="isAuthenticated()" th:href="#{/myProfile}">
<button type="button" class="btn btn-outline-dark">
<i class="fa fa-id-card"></i> Account
</button>
</a>
<a sec:authorize="isAuthenticated()" th:href="#{/logout}">
<button type="button" class="btn btn-outline-dark">
<i class="fa fa-power-off"></i> log-out
</button>
</a>
</div>
</nav>
</div>
<!-- Account modal -->
<div class="modal fade" id="accountAccess" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Account Login and Creation
</h5>
</div>
<div class="modal-body">
<ul class="nav nav-tabs" role="tablist">
<li class="nav-item" th:classappend="${classActiveNewAccount}? 'active'">
<a class="nav-link" data-toggle="tab" href="#tab-1" role="tab">Sign up</a>
</li>
<li class="nav-item" th:classappend="${classActiveLogin}? 'active'">
<a class="nav-link active" data-toggle="tab" href="#tab-2" role="tab">User Login</a>
</li>
<li class="nav-item" th:classappend="${classActiveForgetPassword}? 'active'">
<a class="nav-link" data-toggle="tab" href="#tab-3" role="tab">Forgot Password</a>
</li>
</ul>
<div class="tab-content" style="margin-top: 10px;">
<!-- New User -->
<div class="tab-pane fade" id="tab-1" role="tabpanel" th:classappend="${classActiveNewAccount}? 'in active'">
<form th:action="#{/newUser}" method="post">
<div class="container">
<div class="form-group">
<label for="email">Email Address</label>
<div class="alert alert-danger" th:if="${emailExists}">"Email already exists"</div>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Email Address" />
</div>
<div class="form-group">
<label for="NewUsername">Username</label>
<div class="alert alert-danger" th:if="${usernameExists}">"Username already exists"</div>
<input type="text" class="form-control" id="newUsername" name="NewUsername" tabindex="0" placeholder="Enter Username" />
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-outline-dark btn-sm">
<i class="fa fa-refresh"></i> Reset
</button>
<button type="button" class="btn btn-outline-dark btn-sm">
<i class="fa fa-user-plus"></i> Create New Account
</button>
</div>
</form>
</div>
<!-- login -->
<div class="tab-pane fade show active" id="tab-2" role="tabpanel" th:classappend="${classActiveLogin}? 'active'">
<div class="alert alert-danger" th:if="${param.error != null}">
<small>Please check your credentials and try again.</small>
</div>
<form th:action="#{/login}" method="post">
<div class="container">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter Username" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter Password" />
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-outline-dark btn-sm">
<i class="fa fa-sign-in"></i> Log-In
</button>
</div>
</form>
</div>
<!-- Forgot password -->
<div class="tab-pane fade" id="tab-3" role="tabpanel" th:classappend="${classActiveForgetPassword}? 'in active'">
<div th:if="${emailNotExist}" class="alert alert-danger">Email does not exist</div>
<div th:if="${forgetPasswordEmailSent}" class="alert alert-success">Please check your email for password reset token.</div>
<form action="">
<div class="container">
<div class="form-group">
<label for="recoverEmail">User Email</label>
<input type="email" class="form-control" id="recoverEmail" placeholder="Enter Recovery Email" name="email" />
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-outline-dark btn-sm">
<i class="fa fa-external-link-square"></i> Submit
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div th:fragment="body-bottom-scripts">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" type="text/javascript"></script>
<script src="/js/bootstrap.min.js" type="text/javascript"></script>
</div>
</body>
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.digitalblasphemy.domain.User;
import com.digitalblasphemy.domain.security.PasswordResetToken;
import com.digitalblasphemy.domain.security.Role;
import com.digitalblasphemy.domain.security.UserRole;
import com.digitalblasphemy.service.UserService;
import com.digitalblasphemy.service.impl.UserSecurityService;
import com.digitalblasphemy.utility.MailConstructor;
import com.digitalblasphemy.utility.SecurityUtility;
#Controller
public class HomeController {
#Autowired
private JavaMailSender mailSender;
#Autowired
private MailConstructor mailConstructor;
#Autowired
private UserService userService;
#Autowired
private UserSecurityService userSecurityService;
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping("/myAccount")
public String myAccount() {
return "myAccount";
}
#RequestMapping("/login")
public String login(Model model) {
model.addAttribute("classActiveLogin", true);
return "myProfile";
}
#RequestMapping("/forgetPassword")
public String forgetPassword(
HttpServletRequest request,
#ModelAttribute("email") String email,
Model model
) {
model.addAttribute("classActiveForgetPassword", true);
User user = userService.findByEmail(email);
if (user == null) {
model.addAttribute("emailNotExist", true);
return "index";
}
String password = SecurityUtility.randomPassword();
String encryptedPassword = SecurityUtility.passwordEncoder().encode(password);
user.setPassword(encryptedPassword);
userService.save(user);
String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token);
String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
SimpleMailMessage newEmail = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user, password);
mailSender.send(newEmail);
model.addAttribute("forgetPasswordEmailSent", "true");
return "index";
}
#RequestMapping(value = "/newUser", method = RequestMethod.POST)
public String newUserPost(
HttpServletRequest request,
#ModelAttribute("email") String userEmail,
#ModelAttribute("username") String username,
Model model
) throws Exception {
model.addAttribute("classActiveNewAccount", true);
model.addAttribute("email", userEmail);
model.addAttribute("username", username);
if (userService.findByUsername(username) != null) {
model.addAttribute("usernameExists", true);
return "index";
}
if (userService.findByEmail(userEmail) != null) {
model.addAttribute("emailExists", true);
return "index";
}
User user = new User();
user.setUsername(username);;
user.setEmail(userEmail);
String password = SecurityUtility.randomPassword();
String encryptedPassword = SecurityUtility.passwordEncoder().encode(password);
user.setPassword(encryptedPassword);
Role role = new Role();
role.setRoleId(1);
role.setName("ROLE_USER");
Set < UserRole > userRoles = new HashSet < > ();
userRoles.add(new UserRole(user, role));
userService.createUser(user, userRoles);
String token = UUID.randomUUID().toString();
userService.createPasswordResetTokenForUser(user, token);
String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
SimpleMailMessage email = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user, password);
mailSender.send(email);
model.addAttribute("emailSent", "true");
return "myAccount";
}
#RequestMapping("/newUser")
public String newUser(
Locale locale,
#RequestParam("token") String token,
Model model) {
PasswordResetToken passToken = userService.getPasswordResetToken(token);
if (passToken == null) {
String message = "Invalid Token.";
model.addAttribute("message", message);
return "redirect:/badRequest";
}
User user = passToken.getUser();
String username = user.getUsername();
UserDetails userDetails = userSecurityService.loadUserByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
model.addAttribute("user", user);
model.addAttribute("classActiveEdit", true);
return "myProfile"; //possibly change to index page
}
}
I have this in my Application.java file to create a user for testing purposes.
#Override
public void run(String...args) throws Exception {
User user1 = new User();
user1.setFirstName("Kyle");
user1.setLastName("Drew");
user1.setUsername("kd");
user1.setPassword(SecurityUtility.passwordEncoder().encode("p"));
user1.setEmail("kd#me.com");
Set < UserRole > userRoles = new HashSet < > ();
Role role1 = new Role();
role1.setRoleId(1);
role1.setName("ROLE_USER");
userRoles.add(new UserRole(user1, role1));
userService.createUser(user1, userRoles);
}
Here is a picture of the variables after debugging.

You can avoid this exception by checking if the user is null.
<span style="font-style: italic;" th:text="${user != null} ? ${#strings.toUpperCase(user.username)} : 'user is null'"></span>
But, better approach will be to make sure that user won't be added into model without being initialized.

make sure your user object is not null before you putting into the model

I figured out the issue. In the SecurityConfig.Java file I did not have the .loginPage pointing to the correct location which was creating the exception.
http
.csrf().disable().cors().disable()
.formLogin().failureUrl("/login?error").defaultSuccessUrl("/")
.loginPage("/login").permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/?logout").deleteCookies("remember-me").permitAll()
.and()
.rememberMe();
}

Related

Conversion of 3 files to user desired output using Angular and springboot

I'm trying to upload multiple files to springboot server from angular but I don't know why I'm getting error.But in postman the code is working fine and I'm able to upload files and output format.
I'm getting this error in browser
HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "OK", url: 'http://localhost:8080/file/Upload', ok: false, …}
Error in backend terminal:
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'fileN' is not present]
springboot restapi:
#postMapping(value="/Upload")
public ResponseEntity<List<String>> uploadFiles(#RequestParam ("fileN")List<MultipartFile> multipartFiles,#RequestParam("fileFormat")String id) throws IOException, FOPException, TransformerException{
List<String> filenames = new ArrayList<>();
try{
for(MultipartFile file : multipartFiles){
String filename = StringUtils.cleanPath(file.getOriginalFilename());
Path fileStorage = get(DIRECTORY, filename).toAbsolutePath().normalize();
copy(file.getInputStream(), fileStorage, REPLACE_EXISTING);
filenames.add(filename);
}
fileConversion.Convert(id);
}
catch (Exception e){
e.printStackTrace();
}
return ResponseEntity.ok().body(filenames);
user service:
constructor(private http: HttpClient){}
uploadFile(formData: FormData): Observable<any>{
const headerDist = {
'Access-Control-Allow-Origin': '*';
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
'access-control-allow-credentials':'true'
'Content-Type': 'multipart/form data; boundary=Inflow'
}
const requestOptions = {
headers: new HttpHeaders(headerDist),
};
return this.http.post('http://localhost:8080/file/Upload',formData,requestOptions);
}
appcomponent:
onSubmit(){
const formData = new formData();
formData.append('fileN', this.angForm.get('file1').value);
formData.append('fileN', this.angForm.get('file2').value);
formData.append('fileN', this.angForm.get('file3').value);
formData.append('fileN', this.angForm.get('fileFormat').value);
this.userService.uploadFile(formData).subscribe (
(res) => console.log(res),
(err) => console.log(err)
)};
html:
<h2 id="zone" xmlns="http://www.w3.org/1999/html">File Conversions</h2>
<form [formGroup]="angForm" enctype="multipart/form-data" (ngSubmit)="onSubmit()" >
<div class="main">
<div class="classOne">
<div class="form-two">
<input type="file" class="file-input" formControlName="file1" id="ixml" value="" accept="xml/*" required (change)='uploadF($any($event.target).files)' #open>
<div class="file-upload">
<p class="para-tag">Input XML :</p>
<button mat-raised-button color="primary" class="upload-btn" (click)="open.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file1'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file1'].errors.required"></div>
</div>
<div class="classTwo">
<div class="form-two">
<input type="file" class="file-input" formControlName="file2" id="udtd" value="" accept="dtd/*" required (change)="uploadFile($event.target.files)"#ele>
<div class="file-upload">
<p class="para-tag">Upload DTD : </p>
<button mat-raised-button color="primary" class="upload-btn" (click)="ele.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file2'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file2'].errors.required"></div>
</div>
<div class="classThree">
<div class="form-two">
<input type="file" class="file-input" formControlName="file3" id="uxsl" value="" accept="xsl/*" required (change)="uploading($event.target.files);"#choose>
<div class="file-upload">
<p class="para-tag">Upload XSL : </p>
<button mat-raised-button color="primary" class="upload-btn" (click)="choose.click()">Choose File</button>
</div>
</div>
</div>
<div *ngIf="angForm.controls['file3'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['file3'].errors.required"></div>
</div>
<div class="classFour">
<p class="para-tag-two">Choose Your Output Format :</p>
<div>
<input type="radio" id="pdf" value="pdf" name="fileFormat" formControlName="fileFormat">
<label for="pdf">PDF</label><br>
<input type="radio" id="ps" value="ps" name="fileFormat" formControlName="fileFormat">
<label for="ps">PostScript</label><br>
<input type="radio" id="png" value="png" name="fileFormat" formControlName="fileFormat">
<label for="png">PNG</label><br>
<input type="radio" id="txt" value="txt" name="fileFormat" formControlName="fileFormat">
<label for="txt">Text</label><br>
<input type="radio" id="print" value="print" name="fileFormat" formControlName="fileFormat">
<label for="print">Print</label><br><br>
</div>
</div>
<div *ngIf="angForm.controls['fileFormat'].invalid" class ="alert alert-danger">
<div *ngIf="angForm.controls['fileFormat'].errors.required"></div>
</div>
<div class="submit">
<button style="width:100px;" type="submit" [disabled]="angForm.invalid" mat-raised-button color="warn"disabled="true" >Submit</button>
</div>
</div>
</form>

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.

How to bind an input value in a list to a bean attribute with Spring

I need to bind an object with a list of objects as an attribute. It is a static list and it is created and partially filled in the Controller. It is displayed correctly in the view, however the value in the input field is not set when the form is sent to the controller. I did some research and found several similar questions, however none of the proposed solutions worked for me.
edit.jsp
<c:forEach items="${priceConfigurationForm.priceList}" var="price" varStatus="priceStatus">
<tr>
<td>
<spring:bind path="priceConfigurationForm.priceList[${priceStatus.index}].country">
${price.country}
<input type="hidden" name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>"/>
</spring:bind>
</td>
<td>
<spring:bind path="priceConfigurationForm.priceList[${priceStatus.index}].amount">
<input type="text" name="price" value="${price.amount}"/>
<input type="hidden"
name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>"/>
</spring:bind>
</td>
<td>
<spring:bind path="priceConfigurationForm.priceList[${priceStatus.index}].currency">
${price.currency}
<input type="hidden" name="<c:out value="${status.expression}"/>"
id="<c:out value="${status.expression}"/>"
value="<c:out value="${status.value}"/>"/>
</spring:bind>
</td>
</tr>
</c:forEach>
Abstract from Controller populating the list:
#RequestMapping(value = "/price/create", method = RequestMethod.GET)
public String toCreatePriceConfiguratioView(Model model) {
log.info("::createPriceConfiguration: {}");
final PriceConfigurationForm priceConfigurationForm = new PriceConfigurationForm();
final List<PriceConfigurationForm.Price> prices = new ArrayList<>();
for (Country country : Country.values()) {
PriceConfigurationForm.Price price = new PriceConfigurationForm.Price();
price.setAmount(100);
price.setCountry(country.getCountryCode());
price.setCurrency(country.getCurrency());
prices.add(price);
}
priceConfigurationForm.setPriceList(prices);
model.addAttribute("priceConfigurationForm", priceConfigurationForm);
return "/secured/sources/onboarding/price/edit";
}
Abstract from Controller for storing the list:
#RequestMapping(value = "/price/create", method = RequestMethod.POST)
public String createPriceConfiguration(Model model, #ModelAttribute("priceConfigurationForm") #Valid PriceConfigurationForm priceConfigurationForm, BindingResult bindingResult, RedirectAttributes attributes) {
log.info("::createPriceConfiguration {}", priceConfigurationForm);
// TODO: Validate, before create
/* transform form to domain object */
PriceConfiguration configuration = PriceConfigurationForm.toPriceConfiguration(priceConfigurationForm);
onboardingApi.createPriceConfiguration(configuration);
attributes.addFlashAttribute("message", success("price configuration saved", priceConfigurationForm.getName()));
return "/secured/sources/onboarding/price/index";
}
Object:
#Data
public class PriceConfigurationForm {
private String name;
private String description;
private List<Price> priceList;
private Map<String, Long> countryToPriceMap;
public static PriceConfiguration toPriceConfiguration(PriceConfigurationForm form) {
final PriceConfiguration pc = new PriceConfiguration();
pc.setName(form.getName());
pc.setDescription(form.getDescription());
final Map<String, Long> prices = form.getPriceList().stream().collect(toMap(Price::getCountry, Price::getAmount));
pc.setCountryToPriceMap(prices);
return pc;
}
#Data
public static class Price {
private String country;
private long amount;
private String currency;
}
}
This is example of how I sucessfully parsed nested objects in one project :
<c:forEach var="block" items="${newplaceform.blocks}" varStatus="counter">
<fieldset data-block-order="${counter.index}" data-block-index="${counter.index}">
<c:if test='${block.type=="quizSingleAnswer"}'>
<legend><s:message code='blocks.type.quizSingleAnswer'/> <a class="glyphicon glyphicon-move move-block pull-right" href="#"></a><a data-remove="block" class="glyphicon glyphicon-remove pull-right" href="#"></a><a data-reordering="up" class="glyphicon glyphicon-chevron-up pull-right" href="#"></a><a data-reordering="down" class="glyphicon glyphicon-chevron-down pull-right" href="#"></a></legend>
<div class="form-group production-hide">
<label class="col-sm-3 control-label">id:</label>
<div class="col-sm-9"><input type="text" name="blocks[${counter.index}].id" value="${block.id}" data-row="blockId" data-disabled class="form-control"/></div>
</div>
<div class="form-group production-hide">
<label class="col-sm-3 control-label">type:</label>
<div class="col-sm-9"><input type="text" name="blocks[${counter.index}].type" value="${block.type}" data-disabled class="form-control"/></div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"><s:message code='blocks.description'/>:</label>
<div class="col-sm-9"><textarea class="form-control" name="blocks[${counter.index}].description" data-description rows="3">${block.description}</textarea></div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="col-sm-6 control-label">
<label class="inner-header"><s:message code='blocks.answers'/>:</label>
</div>
<div class="col-sm-6">
<div class="btn-group m-t-9">
<a class="btn btn-primary btn-xs" href="#" data-add-answer data-add-answer-block-index="${counter.index}"><i class="glyphicon glyphicon-plus"></i> <s:message code="blocks.add-answer" /></a>
</div>
</div>
</div>
</div>
<div class="row quiz-answers" data-count-answer="${block.answers.size()}">
<c:forEach var="answer" items="${block.answers}" varStatus="counterInner">
<div class="col-sm-6">
<fieldset>
<legend>
<div class="bootstrap-center">
<span><s:message code="blocks.answerNo"/> ${counterInner.index+1}</span>
<a data-remove="answer" class="glyphicon glyphicon-remove pull-right" href="#"></a>
</div>
</legend>
<div class="form-group production-hide">
<label class="col-sm-6 control-label">id:</label>
<div class="col-sm-6"><input type="text" name="blocks[${counter.index}].answers[${counterInner.index}].id" value="${answer.id}" data-row="answerId" data-disabled class="form-control"/></div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label"><s:message code="blocks.answer"/>:</label>
<div class="col-sm-6"><input type="text" name="blocks[${counter.index}].answers[${counterInner.index}].text" value="${answer.text}" class="form-control"/></div>
</div>
<div class="form-group">
<div class="col-sm-6 col-sm-offset-6">
<div class="checkbox">
<label>
<input type="checkbox" name="blocks[${counter.index}].answers[${counterInner.index}].right" value="true" ${answer.checked()}/>
<s:message code="blocks.right"/>
</label>
</div>
</div>
</div>
</fieldset>
</div>
</c:forEach>
</div>

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