title: Add an object to database by Ajax and Spring MVC
body: <p>I follow this <a href="http://www.raistudies.com/spring/spring-mvc/ajax-spring-mvc-3-annonations-jquery/" rel="nofollow noreferrer">Link</a> 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 : <code>com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'login' cannot be null</code> . this is my Ajax function :</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      $(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 + "&amp;prenom_=" + prenom + "&amp;login_="+ login+ "&amp;password_="+password+"&amp;role_="+role + "&amp;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);
              }
              });
              }
  &lt;/script&gt;
  </code></pre>
  
  <p>this is my form :</p>
  
  <pre><code>            &lt;div id="info"&gt;&lt;/div&gt;
  
              &lt;form:form name="ajf"
                  action="${pageContext.request.contextPath}/ajouter_user"
                  method="post" commandName="user"&gt;
  
                  &lt;table id="tabmenu"&gt;
  
  
                      &lt;tr&gt;
                          &lt;td id="idtab"&gt;Nom :&lt;/td&gt;
                          &lt;td&gt;&lt;form:input type="text" path="nom" id="nom_"
                                  class="round default-width-input" name="name_" /&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;form:errors path="nom" Class="errorbox" /&gt;&lt;/td&gt;
                      &lt;/tr&gt;
                      &lt;tr&gt;
                          &lt;td id="idtab"&gt;Prénom :&lt;/td&gt;
                          &lt;td&gt;&lt;form:input type="text" path="prenom" name="prenom_"
                                  id="prenom_" class="round default-width-input" /&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;form:errors path="prenom" cssClass="errorbox" /&gt;
                      &lt;/tr&gt;
                      &lt;tr&gt;
                          &lt;td id="idtab"&gt;Login :&lt;/td&gt;
                          &lt;td&gt;&lt;form:input type="text" path="login" name="login_"
                                  id="login_" cssClass="round default-width-input" /&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;form:errors path="login" cssClass="errorbox" /&gt;&lt;/td&gt;
                      &lt;/tr&gt;
  
                      &lt;tr&gt;
                          &lt;td id="idtab"&gt;Password :&lt;/td&gt;
                          &lt;td&gt;&lt;form:input type="password" path="password"
                                  id="password_" name="pass_" class="round default-width-input" /&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;form:errors path="password" cssClass="errorbox" /&gt;&lt;/td&gt;
  
                      &lt;/tr&gt;
  
                      &lt;tr&gt;
                          &lt;td id="idtab"&gt;Séléctionner un rôle :&lt;/td&gt;
                          &lt;td&gt;&lt;form:select path="role" id="role"&gt;
                                  &lt;form:option value="" label="" /&gt;
                                  &lt;form:option value="ROLE_ADMIN"&gt;Administrateur&lt;/form:option&gt;
                                  &lt;form:option value="ROLE_USER"&gt;Simple utilisateur&lt;/form:option&gt;
                              &lt;/form:select&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;form:errors path="role" cssClass="errorbox" /&gt;&lt;/td&gt;
                      &lt;/tr&gt;
                      &lt;tr&gt;
                          &lt;td id="idtab"&gt;Activé :&lt;/td&gt;
                          &lt;td&gt;&lt;form:input type="checkbox" value="true" path="enable"
                                  id="enable_" /&gt; Oui&lt;/td&gt;
                      &lt;/tr&gt;
                      &lt;tr&gt;&lt;/tr&gt;
                      &lt;tr&gt;&lt;/tr&gt;
                      &lt;tr&gt;
                          &lt;td&gt;&lt;input
                              class="button round blue image-right ic-right-arrow"
                              type="submit" value="Créer" onclick="doAjaxPost()" /&gt;&lt;/td&gt;
                          &lt;td&gt;&lt;input
                              class="button round blue image-right ic-right-arrow"
                              type="reset" value="Initialiser" /&gt;&lt;/td&gt;
                      &lt;/tr&gt;
  
                  &lt;/table&gt;
              &lt;/form:form&gt;
  </code></pre>
  
  <p>The Controller :</p>
  
  <pre><code>@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;
      }
  </code></pre>
  
  <p>Also I get get the message " <strong>User has been added to the list.</strong> " in another empty page not in my div which has the id="info" as it shown in the code. What is the problem ?
  <img src="https://i.stack.imgur.com/MRwzY.png" alt="enter image description here"></p>
  
  <p>**////// the whole exception \\**</p>
  
  <pre><code>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)
  </code></pre>
  
  <p><strong>The method DAO</strong></p>
  
  <pre><code>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;}
  
          }
  </code></pre>