SSM フレームワークは Ajax を使用してページの追加、削除、変更、確認を行います (シンプルで理解しやすい)

1. 最終ページ効果

ここに画像の説明を挿入します
ここに画像の説明を挿入します

2. Ajax のレビュー

2.1. ajax とは何ですか?

async: false は ajax のパラメータで、リクエストを非同期で実行するかどうかを示します。async が false の場合、リクエストは同期的に実行されます。つまり、リクエストが完了する前にブラウザがロックされ、ユーザーは他の操作を実行できなくなります。この方法はユーザー エクスペリエンスに影響を与えるため、通常は推奨されません。async が true の場合、リクエストは非同期で実行されます。つまり、リクエストの処理中にブラウザはロックされず、ユーザーは他の操作を実行できます。この方法は、ページの応答速度とユーザー エクスペリエンスを向上させることができるため、より一般的に使用されます。

2.2. ajax の特徴は何ですか?
  1. 非同期通信: Ajax は、バックグラウンドでサーバーとデータを交換することで、ページ全体をリロードすることなく、ページのコンテンツを非同期的に更新できます。これにより、ユーザー エクスペリエンスが向上し、不必要なネットワーク リクエストとページの読み込み時間が削減されます。
  2. ページの更新は不要: 従来の Web アプリケーションでは、新しいデータを取得したり、新しいコンテンツを表示したりするためにページを更新する必要があります。Ajax は、ページ全体を更新することなく、部分的な更新を通じてページのコンテンツを動的に変更することができ、よりスムーズなユーザー インターフェイスを提供します。
  3. 標準テクノロジに基づく: Ajax は、HTML、CSS、JavaScript、XML (現在は JSON に置き換えられることが一般的です) などの標準 Web テクノロジを使用し、サーバー側テクノロジとは何の関係もありません。これにより、開発者は既存のテクノロジーやツールを簡単に使用できるようになります。
  4. ユーザー エクスペリエンスの強化: Ajax を使用することで、リアルタイム検索、自動入力、非更新フォーム送信などの機能が実現され、ユーザーと Web アプリケーション間の対話エクスペリエンスが向上します。
  5. 帯域幅消費の削減: Ajax はページ全体のコンテンツではなく、更新が必要なデータのみを送信する必要があるため、ネットワーク帯域幅の消費を削減し、ページの読み込み速度を向上させることができます。
2.3、具体的なプログラミング内容
  1. js送信リクエスト
  2. jsは結果を受け取ります
  3. js更新ページ

3. Jquery は Ajax を実装します

3.1、Jqueryライブラリをインポートする

ここに画像の説明を挿入します

3.2、Jquery静的リソースの解放
	<!--  解决了静态资源的加载问题  -->
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
3.3、属性表示:なし
document.getElementById("myform").style.display="none";
  1. Ajax はページを切り替えません。すべてのコンテンツは 1 ページにあります。style 属性を表示し、値を none に設定するだけで非表示になり、高さを占有しなくなります。
  2. 表示する必要がある場合は、表示値をブロックに設定します。

4 番目、完全な詳細コード

4.1、設定ファイル

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.プロパティ

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

mybatis.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、ロジック層コード

豆の層

  1. MyAjax
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;
    }
}

  1. MyAjaxMapper
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);
}

マッパー

  1. MyAjaxMapper.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>

サービス

  1. MyAjaxService
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);
}

サービスインプル

  1. MyAjaxServiceImpl
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);
    }
}

コントローラ

  1. MyAjaxコントローラー
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. フロントエンド Web コード

  1. listAjax.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>

おすすめ

転載: blog.csdn.net/H20031011/article/details/131661719