Spring mvc,使用AJAX更新数据库中的数据

时间:2018-03-30 12:54:01

标签: ajax database jsp spring-mvc

我再次带着同样的关注,以前没有得到答案。请原谅我重复。

我正在尝试使用AJAX从jsp启用已在我的数据库中注册的用户。很遗憾,我收到以下错误代码。

POST http://localhost:8081/spring_gestionobjetsvolesouperdus_webapp/activerutilisateur/ 405 (Method Not Allowed)    jquery-3.2.1.js:9566

这是我的代码

模型类

@Entity
@Table(name="utilisateur")
public class Utilisateur implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name="username")
    @NotEmpty(message="Veuillez saisir le nom d'utilisateur")
    @UsernameAlreadyExists
    private String username;

    @Column(name="password")
    private String password;

    @Transient
    private String confirmPassword;

    @Column(name="nom_utilisateur")
    private String nomUtilisateur;

    @Column(name="prenom_utilisateur")
    private String prenomUtilisateur;

    @Column(name="date_naissance_utilisateur")
    @DateTimeFormat(pattern="dd-MM-yyyy")
    private Date dateNaissanceUtilisateur;

    @Column(name="lieu_naissance_utilisateur")
    private String lieuNaissanceUtilisateur;

    @Column(name="enable")
    private boolean enable;

    //Getters and Setters

}

Dao实施

public Utilisateur updateUtilisateur(Utilisateur utilisateur) {
    sessionFactory.getCurrentSession().update(utilisateur);
    return utilisateur;
}

控制器

@RequestMapping(value = "/activerutilisateur/", method = RequestMethod.POST)
@ResponseBody
public Utilisateur activerUtilisateur(@RequestBody Utilisateur utilisateur) {
    utilisateur.setEnable(true);
    service.updateUtilisateur(utilisateur);
    return utilisateur;
}

使用AJAX请求的JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <script type="text/javascript" src="<c:url value="/resources/js/jquery-3.2.1.js"/>"></script>
        <script type="text/javascript" src="<c:url value="/resources/js/datatables.min.js"/>"></script> 
        <link rel="stylesheet" type="text/css" href="<c:url value="/resources/css/datatables.min.css"/>"/>
        <link rel="stylesheet" type="text/css" href="<c:url value="/resources/bootstrap-3.3.7/dist/css/bootstrap.min.css"/>" />
        <link rel="stylesheet" type="text/css" href="<c:url value="/resources/css/style.css"/>" />
        <script type="text/javascript">
            $(document).ready(function() {
                $('#example').dataTable();
            } );
        </script>

        <script>
          function activerUtilisateur(username) {

              var user = {"username" : username}

              $.ajax({
                  contentType: 'application/json',
                  type: 'POST',
                  url: 'activerutilisateur/',
                  data : JSON.stringify(user),

                  error: function(data,error,textStatus){
                      alert(data);
                      console.log(textStatus);
                  },

                  complete: function(data) {
                      console.log(data);
                      console.log('complete done');
                  },

                  success: function(data) {
                      alert('success done');
                  }
              });
          }   
        </script>
        <title>Liste des utilisateurs</title>
    </head>
    <body>
        <div class="generic-container">
            <div class="spacer">
                <div class="panel panel-default">
                    <div class="panel-heading"><span class="lead">Liste des utilisateurs</span></div>
                    <div class="table-top-margin">
                        <table class="table table-striped" id="example">
                            <thead>
                                <tr>
                                    <th>Username</th>
                                    <!-- <th>Password</th> -->
                                    <th>Nom et prénoms</th>
                                    <th>Date de naissance</th>
                                    <th>Lieu de naissance</th>
                                    <th>Actif</th>
                                    <th>Action</th>
                                </tr>
                            </thead>                            
                            <tbody>
                                <c:forEach items="${listUtilisateur}" var="u">
                                    <tr>
                                        <%-- <td><c:out value="${u.idUtilisateur}"></c:out></td> --%>
                                        <td><c:out value="${u.username}"/></td>
                                        <%-- <td><c:out value="${u.password}"/></td> --%>
                                        <td><c:out value="${u.nomUtilisateur} ${u.prenomUtilisateur}"/></td>
                                        <%-- <td><c:out value="${u.dateNaissanceUtilisateur}"></c:out></td> --%>
                                        <td><fmt:formatDate value="${u.dateNaissanceUtilisateur}" pattern="dd-MM-yyyy"/></td>
                                        <td><c:out value="${u.lieuNaissanceUtilisateur}"/></td>
                                        <td>
                                            <c:choose>
                                                <c:when test="${u.enable=='TRUE'}">
                                                    <label class="switch">
                                                      <input type="checkbox" checked="checked">
                                                      <span class="slider round"></span>
                                                    </label>
                                                </c:when>
                                                <c:otherwise>
                                                    <label class="switch">
                                                      <input type="checkbox" id="${u.username}" onclick="activerUtilisateur('${u}')">
                                                      <span class="slider round"></span>
                                                    </label>
                                                </c:otherwise>
                                            </c:choose>
                                        </td>
                                        <td><a href="editerutilisateur?username=${u.username}"><span class="glyphicon glyphicon-edit"></span></a> <a href="supprimerutilisateur?username=${u.username}"><span class="glyphicon glyphicon-trash"></span></a></td>
                                    </tr>
                                </c:forEach>
                            </tbody>                            
                        </table>                    
                    </div>                  
                </div>
            </div>
            <div class="well">
                Nouvel utilisateur ? Inscription <a href="nouvelutilisateur">ici</a> sinon <a href="<%request.getContextPath();%>"> retour</a>
            </div>
        </div>
    </body>
</html>

我在项目中也有spring security配置并找到配置代码:

Spring安全配置

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/editermarque**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="/supprimermarque**" access="hasRole('ROLE_ADMIN')"/>
        <access-denied-handler error-page="/403"/>
        <form-login login-processing-url="/j_spring_security_check" login-page="/login" default-target-url="/" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password"/>
        <logout logout-url="/j_spring_security_logout" logout-success-url="/"/>
        <csrf/>
    </http>

    <authentication-manager>
        <authentication-provider>
            <jdbc-user-service data-source-ref="dataSource" users-by-username-query="select username, password, enable from utilisateur where username=?" authorities-by-username-query="select username, role from utilisateurrole where username=?" role-prefix="ROLE_"/>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

请帮助我找到我做错了什么,再一次为重复道歉。

由于

1 个答案:

答案 0 :(得分:0)