【问题标题】:Add an object to database by Ajax and Spring MVC通过 Ajax 和 Spring MVC 将对象添加到数据库
【发布时间】:2013-05-17 07:43:19
【问题描述】:

我关注此Link,我想将用户插入数据库,然后获得成功消息。我的代码成功地将对象插入数据库,但出现错误:com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'login' cannot be null。这是我的 Ajax 函数:

<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>

这是我的表格:

            <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>

控制器:

@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;
    }

我还收到消息“User has been added to the list.”在另一个空页面中,而不是在我的 div 中,其 id="info" 如代码中所示。问题是什么 ?

**////// 整个异常 \\**

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)

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

        }

【问题讨论】:

  • 你能提供整个堆栈跟踪吗?
  • 请问 Stack-trace 是什么意思?
  • 获取com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'login' cannot be null 事物的异常堆栈跟踪。您可能可以从您的应用程序日志中获取它(也可能打印在您的 IDE 控制台中)
  • 是的,我编辑了我的问题,见上面
  • 我认为您的插入不起作用。该异常似乎表明您正在尝试将空值插入“登录”列。我只能猜测,因为您没有显示您的用户域对象,也没有显示存储过程中涉及的 DAO/服务,但我猜您正在以某种方式抑制错误,这就是您收到错误成功消息的原因。跨度>

标签: ajax spring model-view-controller


【解决方案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,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-01
    • 2016-06-02
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2014-09-27
    • 2013-02-25
    • 1970-01-01
    相关资源
    最近更新 更多