A estrutura SSM usa Ajax para adicionar, excluir, modificar e verificar uma página (simples e fácil de entender)

1. Efeito de página final

Insira a descrição da imagem aqui
Insira a descrição da imagem aqui

2. Revisão do Ajax

2.1. O que é ajax?

async: false é um parâmetro em ajax, que indica se a solicitação deve ser executada de forma assíncrona. Quando async for falso, a solicitação será executada de forma síncrona, ou seja, antes da conclusão da solicitação, o navegador será bloqueado e o usuário não poderá realizar outras operações. Este método geralmente não é recomendado porque afetará a experiência do usuário. Quando async for verdadeiro, a solicitação será executada de forma assíncrona, ou seja, o navegador não será bloqueado durante o processo de solicitação e o usuário poderá realizar outras operações. Este método é mais comumente usado porque pode melhorar a velocidade de resposta e a experiência do usuário da página.

2.2.Quais são as características do ajax?
  1. Comunicação assíncrona: o Ajax pode atualizar o conteúdo da página de forma assíncrona, sem recarregar a página inteira, trocando dados com o servidor em segundo plano. Isso melhora a experiência do usuário e reduz solicitações de rede desnecessárias e tempos de carregamento de página.
  2. Não é necessária atualização de página: os aplicativos da Web tradicionais precisam atualizar a página para obter novos dados ou exibir novo conteúdo. O Ajax pode alterar dinamicamente o conteúdo da página por meio de atualizações parciais sem atualizar a página inteira, proporcionando uma interface de usuário mais suave.
  3. Baseado em tecnologias padrão: Ajax usa tecnologias padrão da Web, como HTML, CSS, JavaScript e XML (agora mais comumente substituído por JSON) e não tem nada a ver com tecnologias do lado do servidor. Isso torna mais fácil para os desenvolvedores usarem tecnologias e ferramentas existentes.
  4. Experiência de usuário aprimorada: Ao usar Ajax, funções como pesquisa em tempo real, preenchimento automático e envio de formulário sem atualização podem ser realizadas, melhorando a experiência interativa entre usuários e aplicativos da web.
  5. Reduza o consumo de largura de banda: Como o Ajax só precisa transmitir os dados que precisam ser atualizados, e não o conteúdo de toda a página, ele pode reduzir o consumo de largura de banda da rede e aumentar a velocidade de carregamento da página.
2.3, conteúdo de programação específico
  1. js enviar solicitação
  2. js recebe resultados
  3. página de atualização js

3. Jquery implementa Ajax

3.1, importe a biblioteca Jquery

Insira a descrição da imagem aqui

3.2, Liberar recursos estáticos do Jquery
	<!--  解决了静态资源的加载问题  -->
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
3.3, exibição de atributo: nenhum
document.getElementById("myform").style.display="none";
  1. Ajax não troca de página. Todo o conteúdo está em uma página. Você só precisa exibir o atributo style e definir o valor como none para torná-lo invisível e não ocupar a altura.
  2. Se precisar ser exibido, defina o valor de exibição para bloquear

Quarto, código detalhado completo

4.1, arquivo de configuração

aplicaçãoContext.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.properties

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, código da camada lógica

camada de feijão

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

camada

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

mapeador

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

serviço

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

serviçoimpl

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

controlador

  1. MeuAjaxController
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. Código web front-end

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

Acho que você gosta

Origin blog.csdn.net/H20031011/article/details/131661719
Recomendado
Clasificación