org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NumberFormatException: null - spring

Im trying to do full text search with spring data mongodb with all attributes of my model.
this the model:
#Document
public class Offre {
#Id
private String id;
#TextIndexed
private String titreOffre;
#TextIndexed
private String descriptionOffre;
#TextIndexed
private String date;
#TextIndexed
private String lieu;
}
the repository
public interface OffreRepository extends MongoRepository<Offre, String>, OffreRepositoryCustom,PagingAndSortingRepository<Offre, String> {
Offre findById(String id);
List<Offre> findAll();
}
public interface OffreRepositoryCustom {
public List<Offre> findFullTextSearch(String term);
}
public class OffreRepositoryImpl implements OffreRepositoryCustom{
#Override
public List<Offre> findFullTextSearch(String term){
Query query2 = new Query();
query2.addCriteria(Criteria.where("titreOffre").regex(term));
return mongoTemplate.find(query2, Offre.class);
}
}
this the service:
public class OffreService {
#Autowired
private OffreRepository offreRepository;
private OffreMapper mapper = new OffreMapper();
#Autowired
MongoTemplate template;
private Logger logger = Logger.getLogger(UserService.class);
public List<OffreUi> findFullTextSearch(String term) {
return mapper.toUIBean(offreRepository.findFullTextSearch(term));
}
}
this the controller
#Controller
#RequestMapping("/offres")
public class OffreController {
#Autowired
private OffreService service;
private Logger logger = Logger.getLogger(OffreController.class);
private DataTableResponseMap<OffreUi> offreResponseMap = new DataTableResponseMap<OffreUi>();
#RequestMapping (value = "/fulltext/{searchTerm}", method = RequestMethod.GET)
public String getfullPage(#RequestParam(value = "searchTerm", required = false) String searchTerm,Model model) {
model.addAttribute("offres", service.findFullTextSearch(searchTerm));
return "offre/fulltext";
}
#RequestMapping(value = "/fulltext")
public #ResponseBody
Map<String, ? extends Object> fulltext(
#RequestParam(required = false) String iDisplayStart,
#RequestParam(required = false) String iDisplayLength,
#RequestParam(value = "searchTerm", required = false) String searchTerm,
#RequestParam(required = false) String iSortingCols) {
int pageLength = Integer.parseInt(iDisplayLength);
int startPage = Integer.parseInt(iDisplayStart) / pageLength;
Pageable pageable = new PageRequest(startPage, pageLength);
Page<OffreUi> offres = (Page<OffreUi>) service.findFullTextSearch(searchTerm);
return offreResponseMap.mapOK(offres.getContent(),offres.getTotalElements());
}
}
this my view :
search.jsp:
<html lang="en">
<jsp:include page="../menu/header.jsp" />
<body>
<jsp:include page="../menu/topMenu.jsp" />
<div>
<form method="get"action="<c:url value='/offres/fulltext?searchTerm=${searchTerm}'/>">
<input type="text" name="searchTerm" id="searchTerm" value="searchTerm"/>
<input class="btn btn-primary" type="submit" value="Save">
</form>
</div>
</body>
</html>
and fulltextsearch.jsp
<html lang="en">
<jsp:include page="../menu/header.jsp" />
<body>
<jsp:include page="../menu/topMenu.jsp" />
<div class="container-fluid">
<div class="row-fluid">
<div class="span10">
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example" >
<thead>
<tr>
<th width="20%">Titre Offre</th>
<th width="25%">Description Offre</th>
<th width="15%">Date</th>
<th width="15%">Site Entreprise</th>
<th width="15%">Logo Entreprise</th>
<th width="15%">Lieu</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Titre Offre</th>
<th>Description Offre</th>
th>Date</th>
<th>Site Entreprise</th>
<th>Site Entreprise</th>
<th>Lieu</th>
</tr>
</tfoot>
</table>
</div><!--/span-->
<jsp:include page="../menu/rightMenu.jsp" />
</div><!--/row-->
<hr>
<footer>
<p>© Faycel Gsouma</p>
</footer>
</div><!--/.fluid-container-->
<jsp:include page="../menu/includeScripts.jsp" />
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "<c:url value="/offres/fulltext?searchTerm=${searchTerm}"/>",
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"success": fnCallback
} );
},
"aoColumns": [
{ "mData": "titreOffre" },
{ "mData": "descriptionOffre" },
{ "mData": "date" },
{ "mData": "siteEntreprise" },
{ "mData": "logoEntreprise" },
{ "mData": "lieu" },
]
} );
} );
</script>
</body>
</html>
and this error that i get
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NumberFormatException: null
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:943)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
cause mère
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:454)
java.lang.Integer.parseInt(Integer.java:527)
org.sab.sampleqa.web.controller.user.OffreController.fulltext(OffreController.java:185)
org.sab.sampleqa.web.controller.user.OffreController$$FastClassByCGLIB$$46319c43.invoke(<generated>)
org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:713)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
org.springframework.aop.interceptor.CustomizableTraceInterceptor.invokeUnderTrace(CustomizableTraceInterceptor.java:257)
org.springframework.aop.interceptor.AbstractTraceInterceptor.invoke(AbstractTraceInterceptor.java:112)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:646)
org.sab.sampleqa.web.controller.user.OffreController$$EnhancerByCGLIB$$e7945c7b.fulltext(<generated>)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:748)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
note La trace complète de la cause mère de cette erreur est disponible dans les fichiers journaux de Apache Tomcat/8.0.18.

Your parameters are optional strings:
#RequestParam(required = false) String iDisplayStart,
#RequestParam(required = false) String iDisplayLength,
which you then parse:
int pageLength = Integer.parseInt(iDisplayLength);
which causes the NPE.
You should either check for null first:
int pageLength = null == iDisplayLength
? 10
: Integer.parseInt(iDisplayLength);
or use a defaultValue parameter to #RequestParam, e.g.
#RequestParam(required = false, defaultValue="0") String iDisplayStart,
#RequestParam(required = false, defaultValue="10") String iDisplayLength,

Related

Error when i try to update a member of a table

this is my ProdottoController:
package it.catalogo.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import it.catalogo.model.Prodotto;
import it.catalogo.repository.ProdottoRepository;
#Controller
#RequestMapping("/prodotto")
public class ProdottoController {
#Autowired
private ProdottoRepository repo;
#GetMapping("/lista")
public ModelAndView list( #RequestParam(name = "id", required = false) String idProdotto, ModelMap mm) {
if(idProdotto!=null) {
Optional<Prodotto> p = repo.findById(Integer.parseInt(idProdotto));
mm.addAttribute("prodottoDaModificare",p);
}
return new ModelAndView("prodotti", "listaProdotti", repo.findAll());
}
#PostMapping("/add")
public String add(#ModelAttribute("datiProdotto") Prodotto p) {
repo.save(p);
return "redirect:/prodotto/lista";
}
#PostMapping("/update")
public String update(#ModelAttribute("datiProdotto") Prodotto p) {
repo.save(p);
return "redirect:/prodotto/lista";
}
#GetMapping("/delete")
public String delete(#RequestParam("id") String id) {
repo.deleteById(Integer.parseInt(id));
return "redirect:/prodotto/lista";
}
}
Prodotto entity:
package it.catalogo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Prodotto {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "nome")
private String nome;
#Column(name = "descrizione")
private String descrizione;
#Column(name = "prezzo")
private Integer prezzo;
public Prodotto(String nome, String descrizione, Integer prezzo) {
super();
this.nome = nome;
this.descrizione = descrizione;
this.prezzo = prezzo;
}
public Prodotto() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescrizione() {
return descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public Integer getPrezzo() {
return prezzo;
}
public void setPrezzo(Integer prezzo) {
this.prezzo = prezzo;
}
}
This is the view (Freemarker):
<!DOCTYPE html>
<html>
<head>
<title>Catalogo prodotti</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
</head>
<body>
<h1>Catalogo prodotti</h1>
<#if prodottoDaModificare?? >
<h2>Modifica del prodotto - ${prodottoDaModificare.nome}</h2>
<div style="margin: 20px">
<form method="POST" action="update" id="datiProdotto">
<input type="hidden" name="id" value="${prodottoDaModificare.id}"/>
<div>
<label for="nome">Nome</label>
<input type="text" name="nome" value="${prodottoDaModificare.nome}" id="nome">
</div>
<div>
<label for="descrizione">Descrizione</label>
<input type="text" name="descrizione" value="${prodottoDaModificare.descrizione}" id="descrizione">
</div>
<div>
<label for="prezzo">Prezzo</label>
<input type="number" name="prezzo" value="${prodottoDaModificare.prezzo}" id="prezzo">
</div>
<div>
<input type="submit" name="invia" value="Salva modifiche"/S>
</div>
</form>
</div>
<#else>
<h2>Nuovo prodotto</h2>
<div style="margin: 20px">
<form method="POST" action="add" id="datiProdotto">
<div>
<label for="nome">Nome</label>
<input type="text" name="nome" value="" id="nome">
</div>
<div>
<label for="descrizione">Descrizione</label>
<input type="text" name="descrizione" value="" id="descrizione">
</div>
<div>
<label for="prezzo">Prezzo</label>
<input type="number" name="prezzo" value="" id="prezzo">
</div>
<div>
<input type="submit" name="invia" value="Aggiungi"/>
</div>
</form>
</div>
</#if>
<hr>
<h2>Lista prodotti</h2>
<div>
<table class="table">
<thead>
<tr>
<th>Nome</th>
<th>Descrizione</th>
<th>Prezzo</th>
<th>Azioni</th>
</tr>
</thead>
<tbody>
<#list listaProdotti as prodotto>
<tr>
<td>${prodotto.nome}</td>
<td>${prodotto.descrizione}</td>
<td>${prodotto.prezzo}</td>
<td>
Elimina
Modifica
</td>
</tr>
</#list>
</tbody>
</table>
</div>
</body>
</html>
When i try to update a value into the table i've the following error:
FreeMarker template error (DEBUG mode; use RETHROW in production!): The following has evaluated to null or missing: ==> prodottoDaModificare.nome [in template "prodotti.ftl" at line 15, column 47] ---- Tip: It's the step after the last dot that caused this error, not those before it. ---- Tip: If the failing expression is known to legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: ${prodottoDaModificare.nome} [in template "prodotti.ftl" at line 15, column 45] ---- Java stack trace (for programmers): ---- freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134) at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:481) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:401) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:370) at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:100) at freemarker.core.DollarVariable.accept(DollarVariable.java:63) at freemarker.core.Environment.visit(Environment.java:347) at freemarker.core.Environment.visit(Environment.java:353) at freemarker.core.Environment.visit(Environment.java:353) at freemarker.core.Environment.process(Environment.java:326) at freemarker.template.Template.process(Template.java:383) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:391) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:304) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.renderMergedTemplateModel(FreeMarkerView.java:255) at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:179) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1401) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1145) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1084) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1787) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:833)
Your problem is that when you do mm.addAttribute("prodottoDaModificare",p), p is not a Prodotto object, but an Option. And of course, Option has no nome property. Use mm.addAttribute("prodottoDaModificare",p.orElse(null)) (or if the object must be there, then orElseThrow).

Create form dynamically using thymeleaf

I am new in Spring MVC. I'm stuck for more than 24hrs trying to add a dynamic row using thymeleaf. I followed this link and also the thymeleaf documentation In this tutorial but i have not been able to make it work. Clicking addRow and removeRow doesn't work. Someone should please help me. Thanks
Here is my Controller code:
#Controller
#SessionAttributes("qualification")
public class QualificationController {
private final QualificationService qualificationService;
private final StaffService staffService;
private final CourseService courseService;
#Autowired
public QualificationController(QualificationService qualificationService,
StaffQualificationService service,
StaffService staffService, CourseService courseService) {
this.qualificationService = qualificationService;
this.staffService = staffService;
this.courseService = courseService;
}
#InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
#GetMapping("/staff/{id}/qualification")
public String initForm(#PathVariable("id") Integer id, Model model) {
Staff staff = staffService.findById(id);
staff.addQualification(new StaffQualification());
model.addAttribute("qualification", staff);
model.addAttribute("qualifications", qualificationService.findAll());
model.addAttribute("courses", courseService.findAll());
return "registration/qualification";
}
#PostMapping(path = "/staff/{id}/qualification/new", params = {"save"})
public String addQualification(#ModelAttribute("qualification")
#Valid Staff staff,
BindingResult result, RedirectAttributes attributes,
SessionStatus status) {
if (result.hasErrors()) {
return "registration/qualification";
}
staffService.save(staff);
attributes.addFlashAttribute("successMessage", "Qualification successfully saved");
status.setComplete();
return "registration/qualification";
}
#PostMapping(path = "/staff/{id}/qualification/new", params = {"addRow"})
public String addRow(final Staff staff, BindingResult result) {
staff.getQuals().add(new StaffQualification());
return "registration/qualification";
}
#PostMapping(params = "removeRow", path = {"/staff/{id}/qualification/new"})
public String removeRow(final Staff staff, final BindingResult result,
final HttpServletRequest request) {
final int rowId = Integer.parseInt(request.getParameter("removeRow"));
staff.removeQualification(staff.getQuals().remove(rowId));
return "registration/qualification";
}
}
My entities:
public class Staff extends NamedEntity {
#NotBlank(message = "First Name is blank")
private String firstName;
#NotBlank(message = "Last Name is blank")
private String lastName;
private String middleName;
#Digits(fraction = 0, integer = 10)
#NotBlank(message = "Please fill in your phone number")
private String phoneNumber;
private boolean married;
private String gender;
#Transient
private int age;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "staff", orphanRemoval = true)
private List<StaffQualification> quals = new ArrayList<>();
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "staff", orphanRemoval = true)
private List<Document> documents = new ArrayList<>();
}
public class StaffQualification extends BaseEntity {
private String qualification;
private String course;
private String school;
#NotNull(message = "Date obtained qualification must be in the past")
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate qualDate;
#ManyToOne
private Staff staff;
}
Thymeleaf code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Staff form</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
th:href="#{https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css}"
integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="justify-content-start">
<div th:include="fragments/bodyHeader.html"></div>
</div>
<div class="main body-content">
<div class="container">
<form th:object="${qualification}" th:action="#{/staff/{id}/qualification/new}" th:method="post">
<div class="alert alert-info" th:if="${successMessage}" th:utext="${successMessage}"></div>
<fieldset>
<legend class="w-auto" th:text="#{qualification.staff}">Staff Qualifications</legend>
<div>
<table id="items" class="table table-bordered">
<thead>
<tr>
<th th:scope="col">#</th>
<th th:scope="col">Title</th>
<th th:scope="col">Course</th>
<th th:scope="col">School</th>
<th th:scope="col" type="date">Date Obtained</th>
<th>
<button type="submit" name="addRow" th:text="#{qualification.row.add}">Add row</button>
</th>
</tr>
</thead>
<tbody id="tbodyContainer">
<tr th:each="row, rowStat : *{quals}">
<td th:text="${rowStat.count}">1</td>
<td>
<label>
<select th:field="*{quals[__${rowStat.index}__].qualification}">
<option th:each="var : ${qualifications}"
th:value="${var.id}"
th:text="${var.name}">
</option>
</select>
</label>
</td>
<td>
<label>
<select th:field="*{quals[__${rowStat.index}__].course}">
<option th:each="let : ${courses}"
th:value="${let.id}"
th:text="${let.name}">
</option>
</select>
</label>
</td>
<td>
<label>
<input type="text" th:field="*{quals[__${rowStat.index}__].school}"
th:errorClass="fieldError"/>
</label>
</td>
<td>
<label>
<input type="date" th:field="*{quals[__${rowStat.index}__].qualDate}"/>
</label>
</td>
<td>
<button type="submit" name="removeRow" th:value="${rowStat.index}"
th:text="#{qualification.row.remove}">Remove row
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<button class="btn btn-primary" name="save" style="margin-right: 50px" type="submit">Save</button>
</div>
</fieldset>
<div class="form-actions row justify-content-center" style="padding-top:10px; padding-right: 200px">
<a th:if="${qualification.id}" href="/staff/{id}/qualification"
th:href="#{/staff/{id}/qualification/(id=${qualification.id})}"
class="btn btn-primary">Next</a>
</div>
</form>
</div>
</div>
</body>
</html>
Account Controller:
#Controller
#SessionAttributes("account")
public class AccountController {
private final PencomService pencomService;
private final StaffService staffService;
private final BankService bankService;
#Autowired
public AccountController(PencomService pencomService, StaffService staffService,
BankService bankService) {
this.pencomService = pencomService;
this.staffService = staffService;
this.bankService = bankService;
}
#InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
#GetMapping("/staff/{id}/account")
public String initCreationForm(#PathVariable("id") Integer staffId, Model model) {
Staff staff = staffService.findById(staffId);
staff.setBankAccount(new BankAccount());
staff.setPencomAccount(new PencomAccount());
model.addAttribute("account", staff);
model.addAttribute("listBanks", bankService.findAll());
model.addAttribute("listPensions", pencomService.findAll());
return "registration/account";
}
#PostMapping("/staff/{id}/account/new")
public String addAccount(#ModelAttribute("account") #Valid Staff staff,
BindingResult result, RedirectAttributes attributes, SessionStatus status) {
if (result.hasErrors()) {
return "registration/account";
} else {
staffService.save(staff);
attributes.addFlashAttribute("successMessage", "Accounts successfully saved");
status.setComplete();
return "/registration/account";
}
}
}
Error Message:
java.lang.NullPointerException: null
at com.chairmo.cadre.controller.AccountController.initCreationForm(AccountController.java:48) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

org.hibernate.QueryParameterException

I am newbie in spring. I'm trying to perform add,delete,edit operation on database through spring and hibernate.delete and add operation are successfully executed but When i am trying to edit by clicking on edit. i'm getting this error:
full stacktrace:
org.hibernate.QueryParameterException: could not locate named parameter [UserId]
at org.hibernate.engine.query.ParameterMetadata.getNamedParameterDescriptor(ParameterMetadata.java:75)
at org.hibernate.engine.query.ParameterMetadata.getNamedParameterExpectedType(ParameterMetadata.java:81)
at org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:413)
at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:383)
at UserDao.userDaoImpl.getUserById(userDaoImpl.java:48)
at UserService.userServiceImpl.getUserById(userServiceImpl.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:108)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy17.getUserById(Unknown Source)
at UserController.userController.edit(userController.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
My jsp: "user.jsp"
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring</title>
</head>
<body>
<h2>Add User Data</h2>
<form:form method="POST" modelAttribute="user" action="/SpringHibernate1/addUser">
<table>
<tr>
<td><form:label path="name">Name:</form:label></td>
<td><form:input path="name" value="${user.name}"/></td>
</tr>
<tr>
<td><form:label path="department">Department:</form:label></td>
<td><form:input path="department" value="${user.department}"/></td>
</tr>
<tr>
<td><form:label path="password">Password:</form:label></td>
<td><form:input path="password" value="${user.password}"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
<h2>List users</h2>
<table align="left" border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
<th>Password</th>
<th>Actions on Row</th>
</tr>
<c:forEach items="${userList}" var="user1">
<tr>
<td><c:out value="${user1.id}"/></td>
<td><c:out value="${user1.name}"/></td>
<td><c:out value="${user1.department}"/></td>
<td><c:out value="${user1.password}"/></td>
<td align="center">Edit | Delete</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Controller Class:" userController.java"
#Controller
public class userController {
#Autowired
private userService userService;
#RequestMapping("/user")
public String listUser(Map<String, Object> map) {
map.put("user", new User());
map.put("userList", userService.listUser());
return "user";
}
#RequestMapping(value = "/addUser",method = RequestMethod.POST)
public String addUser(#ModelAttribute("user")User user, BindingResult result)
{
if(null == user.getId()) {
userService.addUser(user);
}
else {
userService.updateUser(user);
}
return "redirect:/user";
}
#RequestMapping("/delete/{userId}")
public String deleteUser(#PathVariable("userId") Integer userId)
{
userService.deleteUser(userId);
return "redirect:/user";
}
#RequestMapping("/edit/{userId}")
public String edit(#PathVariable("userId")Integer userId,Map<String, Object> map)
{
map.put("user", userService.getUserById(userId));
map.put("userList", userService.listUser());
return "user";
}
}
Dao Implemetation: "userDaoImpl.java"
#Repository
public class userDaoImpl implements userDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
#Override
public void deleteUser(Integer id) {
User user = (User)sessionFactory.getCurrentSession().load(User.class,id);
if(null != user) {
sessionFactory.getCurrentSession().delete(user);
}
}
#Override
#SuppressWarnings("unchecked")
public List<User> listUser() {
return sessionFactory.getCurrentSession().createQuery("from User").list();
}
#Override
public void updateUser(User user) {
sessionFactory.getCurrentSession().update(user);
}
#Override
#SuppressWarnings("unchecked")
public User getUserById(Integer id) {
Session session = sessionFactory.getCurrentSession();
List<User> list = session.createQuery("from User u where u.id = :id").setParameter("UserId",id).list();
return list.size() > 0 ?(User)list.get(0): null;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
need to change as below
List<User> list = session.createQuery("from User u where u.id = :id").setParameter("id",id).list();

Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1 on updating of an entity via hibernate

When trying to update an entity from the controller, I keep getting this exception. Rest assured, thorough research regarding this exception has been made, but none of the suggestions have worked in my case.
I am trying to update the doctor entity by calling hibernate session.update(entity);
Doctor model:
#Entity
#Table(name = "tbl_doctor")
public class Doctor {
private Long id;
private PersonInfo personInfo;
private String licenseNumber;
private User user;
private String specialization;
private String employmentStatus;
private String suffix;
private List<Patient> patients;
//
// #OneToMany
// #JoinTable(name = "Doctor_Appointment", joinColumns = { #JoinColumn(name
// = "doctor_id") }, inverseJoinColumns = { #JoinColumn(name = //
// "appointment_id") })
// private List<Appointment> appointments;
public Doctor() {
super();
user = new User();
personInfo = new PersonInfo();
}
#Override
public String toString() {
String patients= "";
for(Patient p: this.patients) {
patients += p.toString();
}
return "Doctor [id=" + id + ", personInfo=" + personInfo
+ ", licenseNumber=" + licenseNumber + ", user=" + user
+ ", specialization=" + specialization + ", employmentStatus="
+ employmentStatus + ", suffix=" + suffix + ", patients="
+ patients + "]";
}
#Column(name = "fld_license_number")
public String getLicenseNumber() {
return licenseNumber;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "key_user")
public User getUser() {
return user;
}
#Column(name = "fld_specialization")
public String getSpecialization() {
return specialization;
}
#Column(name = "fld_employment_status")
public String getEmploymentStatus() {
return employmentStatus;
}
#Column(name = "fld_suffix")
public String getSuffix() {
return suffix;
}
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "key_patient")
#Fetch(value = FetchMode.SUBSELECT)
public List<Patient> getPatients() {
return patients;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "key_doctor")
public Long getId() {
return id;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "key_person_info")
public PersonInfo getPersonInfo() {
return personInfo;
}
//setters
}
Person info just includes the biodata like first name, last name, sex, birthday etc.
Controller
#RequestMapping(value="/update_doctor.it", method=RequestMethod.POST)
public String updateDoctor(HttpSession session, #ModelAttribute("doctor") Doctor doctor, Model model, #RequestParam("id") long adminId) {
System.err.println("update doctor controller");
String username = session.getAttribute("user").toString();
session.setAttribute("user", username);
doctor.getUser().setEnabled(true);
doctor.getPersonInfo().setDateModified(LocalDate.now());
doctorDao.updateDoctor(doctor);
return "redirect:/view_doctor_profile.it?id=" + doctor.getId();
}
DaoImpl
#Override
public void updateDoctor(Doctor doctor) {
Session session = sessionFactory.getCurrentSession();
session.update(doctor);
}
JSP
form:form class="docForm" method="post" commandName="doctor" action="update_doctor.it?id=${adminUser.getId() }" >
<section>
<header>
<h3>Doctor Information</h3>
</header>
<form:hidden path="id" value="${doctor.id}" />
<ul class="fields">
<li><label>First Name</label>:<form:input value="${doctor.getPersonInfo().getFirstName()}" path="personInfo.firstName" type="text" required="true" /></li>
<li><label>Last Name</label>:<form:input value="${doctor.getPersonInfo().getLastName()}" path="personInfo.lastName" type="text" required="true" /></li>
<li><label>Suffix</label>:<form:input value="${doctor.getSuffix() }" path="suffix" /></li>
<li><label>License Number</label>:<form:input value="${ doctor.getLicenseNumber() }" path="licenseNumber" /></li>
<li><label>Occupation</label>:<form:input value="${doctor.getPersonInfo().getOccupation() }" path="personInfo.occupation" /></li>
<li><label>Specialization</label>:<form:input value="${ doctor.getSpecialization() }" path="specialization" required="true"/></li>
<li><label>Date of Birth</label>:<input value="${doctor.getPersonInfo().getDateOfBirth() }" name="personInfo.dateOfBirth" type="text" id="datepicker" readonly/></li>
<li><label>Gender</label>:
<label>Male</label><form:radiobutton path="personInfo.sex" value="male"/>
<label>Female</Label><form:radiobutton path="personInfo.sex" value="female"/>
</li>
<li><label>Phone Number</label>:<form:input value="${ doctor.getPersonInfo().getContacts().get(0).getPhoneNumber() }" path="personInfo.contacts[0].phoneNumber"/></li>
<li><label>Mobile Number</label>:<form:input value="${ doctor.getPersonInfo().getContacts().get(0).getMobileNumber() }" path="personInfo.contacts[0].mobileNumber" type="text" required="true"/></li>
<li><label>E-mail Address</label>:<form:input value="${ doctor.getPersonInfo().getEmail() }" path="personInfo.email" type="text" required="true"/></li>
</ul>
</section>
<section>
<header><h3>Address</h3></header>
<ul class="fields">
<li><label>Address</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(0).getAddress() }" path="personInfo.addresses[0].address"/></li>
<li><label>City</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(0).getCity() }" path="personInfo.addresses[0].city"/></li>
<li><label>Province</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(0).getProvince() }" path="personInfo.addresses[0].province"/></li>
<li><label>Zip Code</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(0).getZipCode() }" path="personInfo.addresses[0].zipCode" /></li>
</ul>
</section>
<section>
<header><h3>Account Details</h3></header>
<ul class="fields">
<li><label>Username</label>:<form:input value="${ doctor.getUser().getUsername() }" path="user.username" required="true"/></li>
<li><label>Password</label>:<form:password value="${ doctor.getUser().getPassword() }" path="user.password" required="true"/></li>
</ul>
</section>
<section>
<header>
<h3>Hospital Details</h3>
</header>
<ul class="fields">
<li><label>Name</label>:<form:input value="${doctor.getPersonInfo().getCompanyName() }" path="personInfo.companyName"/></li>
<li><label>Employment Status</label>:
<label>Full-time</label><form:radiobutton path="employmentStatus" value="full-time"/>
<label>Part-time</Label><form:radiobutton path="employmentStatus" value="part-time"/>
</li>
<li><label>Phone Number</label>:<form:input value="${ doctor.getPersonInfo().getContacts().get(1).getPhoneNumber()}" path="personInfo.contacts[1].phoneNumber"/></li>
<li><label>Work Mobile Number</label>:<form:input value="${ doctor.getPersonInfo().getContacts().get(1).getPhoneNumber()}" path="personInfo.contacts[1].mobileNumber" /></li>
<li><label>Address</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(1).getAddress() }" path="personInfo.addresses[1].address" /></li>
<li><label>City</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(1).getCity() }" path="personInfo.addresses[1].city"/></li>
<li><label>Province</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(1).getProvince() }" path="personInfo.addresses[1].province" /></li>
<li><label>Zip Code</label>:<form:input value="${ doctor.getPersonInfo().getAddresses().get(1).getZipCode() }" path="personInfo.addresses[1].zipCode" />
</ul>
</section>
<section>
<ul class="btnForm">
<li><span class="btn"><input type="submit"
value="Save" class="btnS"></span></li>
<li><span class="btn"><input type="button"
value="Cancel" class="btnCancel" onClick="viewPotentialsList()"></span></li>
</ul>
Error
SEVERE: Servlet.service() for servlet [emrMVC] in context with path [/emr] threw exception [Request processing failed; nested exception is org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1] with root cause
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:657)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:475)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:270)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy27.updateDoctor(Unknown Source)
at com.ust.emr.controller.admin.EditDoctorController.updateDoctor(EditDoctorController.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I figured it out. A lot of classes or entities are dependent on the doctor, the entity I'm updating. In order for the batch update to execute successfully, I had to place a on the jsp, fetching all the ids of the dependent classes. Thank you!

Add an object to database by Ajax and Spring MVC

I follow this Link and i want to insert a user to database and then get the succes massage. My code insert successfuly the object to database but i get an error : com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'login' cannot be null . this is my Ajax function :
<script type="text/javascript">
$(document).ready(function() {
function doAjaxPost() {
// get the form values
var name = $('#name_').val();
var prenom = $('#prenom_').val();
var login = $('#login_').val();
var password = $('#password_').val();
var role = $('#role_').val();
var enable = $('#enable_').val();
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/ajouter_user",
data: "name_=" + name + "&prenom_=" + prenom + "&login_="+ login+ "&password_="+password+"&role_="+role + "&enable_="+enable,
success: function(response){
// we have the response
$('#info').html(response);
$('#nom_').val('');
$('#prenom_').val('');
$('#login_').val('');
$('#password_').val('');
$('#role_').val('');
$('#enable_').val('');
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
this is my form :
<div id="info"></div>
<form:form name="ajf"
action="${pageContext.request.contextPath}/ajouter_user"
method="post" commandName="user">
<table id="tabmenu">
<tr>
<td id="idtab">Nom :</td>
<td><form:input type="text" path="nom" id="nom_"
class="round default-width-input" name="name_" /></td>
<td><form:errors path="nom" Class="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Prénom :</td>
<td><form:input type="text" path="prenom" name="prenom_"
id="prenom_" class="round default-width-input" /></td>
<td><form:errors path="prenom" cssClass="errorbox" />
</tr>
<tr>
<td id="idtab">Login :</td>
<td><form:input type="text" path="login" name="login_"
id="login_" cssClass="round default-width-input" /></td>
<td><form:errors path="login" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Password :</td>
<td><form:input type="password" path="password"
id="password_" name="pass_" class="round default-width-input" /></td>
<td><form:errors path="password" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Séléctionner un rôle :</td>
<td><form:select path="role" id="role">
<form:option value="" label="" />
<form:option value="ROLE_ADMIN">Administrateur</form:option>
<form:option value="ROLE_USER">Simple utilisateur</form:option>
</form:select></td>
<td><form:errors path="role" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Activé :</td>
<td><form:input type="checkbox" value="true" path="enable"
id="enable_" /> Oui</td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td><input
class="button round blue image-right ic-right-arrow"
type="submit" value="Créer" onclick="doAjaxPost()" /></td>
<td><input
class="button round blue image-right ic-right-arrow"
type="reset" value="Initialiser" /></td>
</tr>
</table>
</form:form>
The Controller :
#RequestMapping(value="/ajouter_user",method=RequestMethod.POST)
public #ResponseBody String addUser(#ModelAttribute User us, BindingResult result ){
String returnText;
if(!result.hasErrors()){
userservice.AddUser(us);
returnText = "User has been added to the list.";
}else{
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
Also I get get the message " User has been added to the list. " in another empty page not in my div which has the id="info" as it shown in the code. What is the problem ?
**////// the whole exception \\**
mai 22, 2013 12:16:10 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Dispatcher] in context with path [/GestionDelegation] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [insert into utilisateurs (login, password, nom, prenom,enable) values (?,?,?,?,?)]; Column 'login' cannot be null; nested exception is com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'login' cannot be null] with root cause
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'login' cannot be null
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3249)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1268)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1541)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1455)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1440)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:102)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:817)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:1)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:586)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:811)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:867)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:875)
at gestion.delegation.dao.ImplIUserDao.AddUser(ImplIUserDao.java:58)
at gestion.delegation.service.ImplIUserService.AddUser(ImplIUserService.java:22)
at gestion.delegation.controller.GestionUserController.addUser(GestionUserController.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The method DAO
public boolean AddUser(User user) {
boolean t=true;
final String User_INSERT1 = "insert into utilisateurs (login, password, nom, prenom,enable) "
+ "values (?,?,?,?,?)";
final String User_INSERT2="insert into roles (login,role) values(?,?)";
/*
* On récupère et on utilisera directement le jdbcTemplate
*/
MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA");
String hash = encoder.encodePassword(user.getPassword(), "");
final String check ="select count(*) from utilisateurs where login = ?";
int result= getJdbcTemplate().queryForInt(check, new Object[]{String.valueOf(user.getLogin())});
if (result==0) {
getJdbcTemplate()
.update(User_INSERT1,
new Object[] {user.getLogin(),
hash, user.getNom(),
user.getPrenom(), user.getEnable(),
});
getJdbcTemplate().update(User_INSERT2, new Object[]{user.getLogin(),user.getRole()});
return t;
}
else { t = false ; return t;}
}
Write your data field as
data:{"name" : name , "prenom" : prenom , "login_" : login , "password_" :password , "role_" :role , "enable_" :enable },
insted of
data: "name_=" + name + "&prenom_=" + prenom + "&login_="+ login+ "&password_="+password+"&role_="+role + "&enable_="+enable,

Resources