Le framework SSM utilise Ajax pour ajouter, supprimer, modifier et vérifier une page (simple et facile à comprendre)

1. Effet de page finale

Insérer la description de l'image ici
Insérer la description de l'image ici

2. Revue Ajax

2.1. Qu'est-ce qu'Ajax ?

async : false est un paramètre en ajax, qui indique s'il faut exécuter la requête de manière asynchrone. Lorsque async est faux, la demande sera exécutée de manière synchrone, c'est-à-dire qu'avant que la demande ne soit terminée, le navigateur sera verrouillé et l'utilisateur ne pourra pas effectuer d'autres opérations. Cette méthode n’est généralement pas recommandée car elle affecterait l’expérience utilisateur. Lorsque async est vrai, la demande sera exécutée de manière asynchrone, c'est-à-dire que le navigateur ne sera pas verrouillé pendant le processus de demande et que l'utilisateur pourra effectuer d'autres opérations. Cette méthode est plus couramment utilisée car elle peut améliorer la vitesse de réponse et l’expérience utilisateur de la page.

2.2.Quelles sont les caractéristiques d'ajax ?
  1. Communication asynchrone : Ajax peut mettre à jour le contenu de la page de manière asynchrone sans recharger la page entière en échangeant des données avec le serveur en arrière-plan. Cela améliore l'expérience utilisateur et réduit les requêtes réseau inutiles et les temps de chargement des pages.
  2. Aucune actualisation de page requise : les applications Web traditionnelles doivent actualiser la page pour obtenir de nouvelles données ou afficher un nouveau contenu. Ajax peut modifier dynamiquement le contenu de la page via des mises à jour partielles sans actualiser la page entière, offrant ainsi une interface utilisateur plus fluide.
  3. Basé sur des technologies standards : Ajax utilise des technologies Web standards, telles que HTML, CSS, JavaScript et XML (maintenant plus communément remplacé par JSON), et n'a rien à voir avec les technologies côté serveur. Cela permet aux développeurs d'utiliser plus facilement les technologies et les outils existants.
  4. Expérience utilisateur améliorée : en utilisant Ajax, des fonctions telles que la recherche en temps réel, la complétion automatique et la soumission de formulaires sans actualisation peuvent être réalisées, améliorant ainsi l'expérience interactive entre les utilisateurs et les applications Web.
  5. Réduire la consommation de bande passante : étant donné qu'Ajax n'a besoin de transmettre que les données qui doivent être mises à jour, plutôt que le contenu de la page entière, il peut réduire la consommation de bande passante du réseau et augmenter la vitesse de chargement des pages.
2.3, contenu de programmation spécifique
  1. js envoyer la demande
  2. js reçoit les résultats
  3. page de mise à jour js

3. Jquery implémente Ajax

3.1, importer la bibliothèque Jquery

Insérer la description de l'image ici

3.2, Publier les ressources statiques Jquery
	<!--  解决了静态资源的加载问题  -->
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
3.3, affichage des attributs : aucun
document.getElementById("myform").style.display="none";
  1. Ajax ne change pas de page. Tout le contenu est sur une seule page. Il vous suffit d'afficher l'attribut style et de définir la valeur sur none pour le rendre invisible et ne pas occuper la hauteur.
  2. S'il doit être affiché, définissez la valeur d'affichage sur bloquer

Quatrièmement, code détaillé complet

4.1, fichier de configuration

applicationContext.xml

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

    http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd

	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd

	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 加载属性文件   -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!-- 创建dbcp2数据源 此数据源可以替换为阿里的 德鲁伊   -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${user}"></property>
        <property name="password" value="${pwd}"></property>
    </bean>
    <!--  整合了sqlSessionFactory 包含了 数据源(dataSource)、配置文件(config)和映射文件(mapper)  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

    <!--  扫描mapper接口  -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xinxi2.dao"></property>
    </bean>

    <!--  扫描业务逻辑层的注解  -->
    <context:component-scan base-package="com.xinxi2"></context:component-scan>

    <!--  引入事务管理器 管理指定的数据源  -->
    <bean id="txMapper" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--  把事务管理管理,变成增强(通知),同时指定了方法的事务传播机制  -->
    <tx:advice id="txAdvice" transaction-manager="txMapper">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>


    <aop:config>
        <aop:pointcut id="servicePointcut" expression="execution(* com.xinxi2.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"></aop:advisor>
    </aop:config>
    <import resource="springmvc.xml"></import>
</beans>

jdbc.propriétés

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/bianlidain?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT-8
user=
pwd=

monbatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--  日志  -->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <property name="reasonable" value="true"/>
            <property name="helperDialect" value="mysql"/>
        </plugin>
    </plugins>
</configuration>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd

    http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd

	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd

	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc.xsd

	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd">

<!--  扫描  -->
    <context:component-scan base-package="com.xinxi2.controller"></context:component-scan>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <!-- Date的日期转换器 -->
                        <value>WriteDateUseDateFormat</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

<!--  常用视图解析器    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=""></property>
    </bean>

<!--  解决了静态资源的加载问题  -->
    <mvc:resources mapping="/static/**" location="/static/"></mvc:resources>
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>

<!--    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">-->
<!--        <property name="exceptionMappings">-->
<!--            <props>-->
<!--                <prop key="java.lang.RuntimeException">error.jsp</prop>-->
<!--            </props>-->
<!--        </property>-->
<!--    </bean>-->

<!--  配置multipartResolver,用于上传文件,使用spring的CommonsMultipartResolver  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxInMemorySize" value="5000000"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

<!--    <mvc:interceptors>-->
<!--        <mvc:interceptor>-->
<!--            <mvc:mapping path="/hello/**"/>-->
<!--            <mvc:exclude-mapping path="/hello/hello04"/>-->
<!--            <bean class="com.Interceptor.LoginInterceptor"></bean>-->
<!--        </mvc:interceptor>-->
<!--    </mvc:interceptors>-->


</beans>
4.2, code de couche logique

couche de haricots

  1. MonAjax
package com.xinxi2.bean;

public class MyAjax {
    
    

    private Integer id;
    private String ajaxname;
    private String ajaxage;

    public Integer getId() {
    
    
        return id;
    }

    public void setId(Integer id) {
    
    
        this.id = id;
    }

    public String getAjaxname() {
    
    
        return ajaxname;
    }

    public void setAjaxname(String ajaxname) {
    
    
        this.ajaxname = ajaxname;
    }

    public String getAjaxage() {
    
    
        return ajaxage;
    }

    public void setAjaxage(String ajaxage) {
    
    
        this.ajaxage = ajaxage;
    }
}

couche

  1. MonAjaxMapper
package com.xinxi2.dao;

import com.xinxi2.bean.MyAjax;

import java.util.List;

public interface MyAjaxMapper {
    
    

    // 查询
    List<MyAjax> getlistMyAjax(MyAjax myAjax);

    // 新增
    int addMyAjax(MyAjax myAjax);

    // 修改
    MyAjax updateById(Integer id);

    // 修改
    int updateMyAjax(MyAjax myAjax);

    // 删除
    int deleteMyAjax(int id);
}

mappeur

  1. MonAjaxMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xinxi2.dao.MyAjaxMapper">

    <resultMap id="MyAjaxinto" type="com.xinxi2.bean.MyAjax">
        <id property="id" column="id"></id>
        <result property="ajaxname" column="ajaxname"></result>
        <result property="ajaxage" column="ajaxage"></result>
    </resultMap>
    <select id="getlistMyAjax" resultType="com.xinxi2.bean.MyAjax" resultMap="MyAjaxinto">
        SELECT id,ajaxname,ajaxage FROM myajax
        <where>
            <if test="id!=null">
                and id=#{id}
            </if>
            <if test="ajaxname!=null">
                and ajaxname=#{ajaxname}
            </if>
            <if test="ajaxage!=null">
                and ajaxage=#{ajaxage}
            </if>
        </where>
    </select>

    <insert id="addMyAjax" useGeneratedKeys="true" keyColumn="id" keyProperty="id" parameterType="com.xinxi2.bean.MyAjax">
        insert into myajax(ajaxname,ajaxage)values(#{ajaxname},#{ajaxage})
    </insert>

    <select id="updateById" parameterType="integer" resultMap="MyAjaxinto">
        SELECT id,ajaxname,ajaxage FROM myajax
        where id=#{id}
    </select>

    <update id="updateMyAjax">
        update myajax
            <set>
                <if test="id!=null">
                    id=#{id},
                </if>
                <if test="ajaxname!=null">
                    ajaxname=#{ajaxname},
                </if>
                <if test="ajaxage!=null">
                    ajaxage=#{ajaxage},
                </if>
            </set>
            where id=#{id}
    </update>

    <delete id="deleteMyAjax" parameterType="integer">
        delete from myajax where id=#{id}
    </delete>
</mapper>

service

  1. MonAjaxService
package com.xinxi2.service;

import com.xinxi2.bean.MyAjax;

import java.util.List;

public interface MyAjaxService {
    
    

    // 查询
    List<MyAjax> getlistMyAjax(MyAjax myAjax);

    // 新增
    int addMyAjax(MyAjax myAjax);

    // 修改
    MyAjax updateById(Integer id);

    // 修改
    int updateMyAjax(MyAjax myAjax);

    // 删除
    int deleteMyAjax(int id);
}

serviceimpl

  1. MonAjaxServiceImpl
package com.xinxi2.service.impl;

import com.xinxi2.bean.MyAjax;
import com.xinxi2.dao.MyAjaxMapper;
import com.xinxi2.service.MyAjaxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MyAjaxServiceImpl implements MyAjaxService {
    
    

    @Autowired
    private MyAjaxMapper myAjaxMapper;

    @Override
    public List<MyAjax> getlistMyAjax(MyAjax myAjax) {
    
    
        return myAjaxMapper.getlistMyAjax(myAjax);
    }

    @Override
    public int addMyAjax(MyAjax myAjax) {
    
    
        return myAjaxMapper.addMyAjax(myAjax);
    }

    @Override
    public MyAjax updateById(Integer id) {
    
    
        return myAjaxMapper.updateById(id);
    }

    @Override
    public int updateMyAjax(MyAjax myAjax) {
    
    
        return myAjaxMapper.updateMyAjax(myAjax);
    }

    @Override
    public int deleteMyAjax(int id) {
    
    
        return myAjaxMapper.deleteMyAjax(id);
    }
}

manette

  1. MonAjaxController
package com.xinxi2.controller;

import com.alibaba.fastjson.JSON;
import com.xinxi2.bean.MyAjax;
import com.xinxi2.service.MyAjaxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/myAjaxController")  // 当前路径
public class MyAjaxController {
    
    

    @Autowired
    private MyAjaxService myAjaxService; // //controller调用 service层

    // 查询
    @RequestMapping("/myAjaxList")  //地址上带UI表示打开页面,不带的表示返回数据
    @ResponseBody  // @RequestBody 注解用于将请求的 body 中的数据绑定到方法的入参上
    public String myAjaxList(MyAjax myAjax){
    
    
        // 调用查询方法
        List<MyAjax> dataList = myAjaxService.getlistMyAjax(myAjax);
        String result = JSON.toJSONString(dataList);
        return result;
    }

    // 新增
    @RequestMapping("/myAjaxadd")  //地址上带UI表示打开页面,不带的表示返回数据
    @ResponseBody   // @RequestBody 注解用于将请求的 body 中的数据绑定到方法的入参上
    public String myAjaxadd(MyAjax myAjax){
    
    
        // 调用新增方法
        myAjaxService.addMyAjax(myAjax);
        return "success";
    }

    // 修改
    @RequestMapping("/myAjaxById")  //地址上带UI表示打开页面,不带的表示返回数据
    @ResponseBody   // @RequestBody 注解用于将请求的 body 中的数据绑定到方法的入参上
    public String myAjaxById(Integer id){
    
    
        // 调用修改方法
        MyAjax myAjax = myAjaxService.updateById(id);
        String result = JSON.toJSONString(myAjax);
        return result;
    }

    // 修改
    @RequestMapping("/myAjaxupdate")  //地址上带UI表示打开页面,不带的表示返回数据
    @ResponseBody  // @RequestBody 注解用于将请求的 body 中的数据绑定到方法的入参上
    public String myAjaxupdate(MyAjax myAjax){
    
    
        // 调用修改方法
        int count = myAjaxService.updateMyAjax(myAjax);
        String result = JSON.toJSONString(count);
        return result;
    }

    // 删除
    @RequestMapping("/myAjaxdelete")  //地址上带UI表示打开页面,不带的表示返回数据
    @ResponseBody  // @RequestBody 注解用于将请求的 body 中的数据绑定到方法的入参上
    public String myAjaxdelete(int id){
    
    
        // 调用删除方法
        myAjaxService.deleteMyAjax(id);
        return "success";
    }
}

5. Code Web frontal

  1. listeAjax.jsp
<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2023/7/10
  Time: 15:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
</head>
<body>

    <table id="dataTbl" border="1">
         <thead>
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th colspan="2">操作</th>
            </tr>
         </thead>
        <tbody id="dataBody">
        <!-- 数据行动态生成 -->
        </tbody>
    </table>
    <button type="button" onclick="addBut()">添加</button>
    <form id="myform">
        <input type="text" id="ajaxname" name="ajaxname" placeholder="姓名"><br>
        <input type="text" id="ajaxage" name="ajaxage" placeholder="年龄"><br>
        <button id="addBtn">添加</button><br>
    </form>

    <form id="myformupdate" >
        <input type="hidden" class="id" name="id">
        <input type="text" class="ajaxname" name="ajaxname" placeholder="姓名"><br>
        <input type="text" class="ajaxage" name="ajaxage" placeholder="年龄"><br>
        <button id="updateBtn">修改</button><br>
    </form>

</body>
<script src="/js/jquery.js"></script>
<script>
    $(function (){
      
      
        document.getElementById("myform").style.display="none";
        document.getElementById("myformupdate").style.display="none";

    })
    function addBut(){
      
      
        document.getElementById("myform").style.display="block";
    }

    // 查询
    function refreshTable(){
      
      
        $.ajax({
      
      
            url:"/myAjaxController/myAjaxList",  // 后端查询数据接口的URL
            type:"get",
            success:function (result){
      
      
                // 清空表格数据
                $("#dataBody").empty();
                // 动态生成表格数据
                var dataBody = $("#dataBody")
                dataBody.html("")
                for (var i=0;i<result.length;i++){
      
      
                    var item = result[i];
                    var tr = document.createElement("tr");
                    tr.innerHTML="<td>"+ result[i].id +"</td>" +
                        "<td>"+ result[i].ajaxname +"</td>" +
                        "<td>"+ result[i].ajaxage +"</td>" +
                        "<td><button type='button' class='updateBtn' οnclick='updatefun("+ item.id +")'>修改</button></td>" +
                        "<td><button type='button' class='deleteBtn'  data-id='" + item.id + "'>删除</button></td>"
                    dataBody.append(tr)
                }
            }
        });
    }

    // 添加数据
    $("#addBtn").click(function (){
      
      
        var MyAjax = $("#myform").serialize();
        $.ajax({
      
      
            url:"/myAjaxController/myAjaxadd", // 后端添加数据接口的URL
            type:"post",
            data:MyAjax,
            dataType: "json",
            success:function (result){
      
      
                // 添加成功后,刷新数据表格
                refreshTable();
            }
        });
    });

    // 修改
    function updatefun(id){
      
      
        document.getElementById("myformupdate").style.display="block";
        $.ajax({
      
      
            url:"/myAjaxController/myAjaxById",  // 后端修改数据接口的URL
            type:"post",
            data:{
      
      
                "id":id
            },
            dataType:"json",
            success:function (result){
      
      
                $(".id").val(result.id);
                $(".ajaxname").val(result.ajaxname);
                $(".ajaxage").val(result.ajaxage);
            }
        });
    }
    // 修改
    $("#myformupdate").submit(function (){
      
      
        var MyAjax = $("#myformupdate").serialize();
        $.ajax({
      
      
            url:"/myAjaxController/myAjaxupdate",   // 后端修改数据接口的URL
            type:"post",
            data:MyAjax,
            dataType: "json",
            success:function (data){
      
      
                refreshTable();
                document.getElementById("myformupdate").style.display="none";
            }
        })
        return false;
    })
    // 删除
    $("body").on("click",".deleteBtn",function (){
      
      
        var id = $(this).attr("data-id");

        $.ajax({
      
      
            url: "/myAjaxController/myAjaxdelete", // 后端删除数据接口的URL
            type: "post",
            data: {
      
      
                id:id
            },
            success:function (result){
      
      
                // 删除成功后,刷新数据表格
                refreshTable();
            }
        });
    });

    // 页面加载完成后,刷新数据表格
    $(document).ready(function (){
      
      
        refreshTable();
    })
</script>
</html>

Je suppose que tu aimes

Origine blog.csdn.net/H20031011/article/details/131661719
conseillé
Classement