1

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 ? enter image description here

**////// 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;}

        }
4

1 回答 1

1

将您的数据字段写为

data:{"name" : name , "prenom" : prenom , "login_" : login , "password_" :password , "role_" :role , "enable_" :enable },

安装的

data: "name_=" + name + "&prenom_=" + prenom + "&login_="+ login+ "&password_="+password+"&role_="+role + "&enable_="+enable,
于 2016-06-07T07:00:49.847 回答