SSM 프레임워크는 Ajax를 사용하여 페이지 추가, 삭제, 수정 및 확인(간단하고 이해하기 쉬움)

1. 최종 페이지 효과

여기에 이미지 설명을 삽입하세요.
여기에 이미지 설명을 삽입하세요.

2. Ajax 리뷰

2.1 아약스란 무엇인가?

async: false는 요청을 비동기적으로 실행할지 여부를 나타내는 ajax의 매개변수입니다. async가 false인 경우 요청은 동기적으로 실행됩니다. 즉, 요청이 완료되기 전에 브라우저가 잠기고 사용자는 다른 작업을 수행할 수 없습니다. 이 방법은 사용자 경험에 영향을 미치기 때문에 일반적으로 권장되지 않습니다. async가 true이면 요청은 비동기적으로 실행됩니다. 즉, 요청 프로세스 중에 브라우저가 잠기지 않으며 사용자는 다른 작업을 수행할 수 있습니다. 이 방법은 페이지의 응답 속도와 사용자 경험을 향상시킬 수 있기 때문에 더 일반적으로 사용됩니다.

2.2 아약스의 특징은 무엇입니까?
  1. 비동기식 통신: Ajax는 백그라운드에서 서버와 데이터를 교환하여 전체 페이지를 다시 로드하지 않고도 페이지의 내용을 비동기적으로 업데이트할 수 있습니다. 이를 통해 사용자 경험이 향상되고 불필요한 네트워크 요청 및 페이지 로드 시간이 줄어듭니다.
  2. 페이지 새로 고침 필요 없음: 기존 웹 애플리케이션은 새 데이터를 얻거나 새 콘텐츠를 표시하기 위해 페이지를 새로 고쳐야 합니다. Ajax는 전체 페이지를 새로 고치지 않고도 부분 업데이트를 통해 페이지의 내용을 동적으로 변경할 수 있어 보다 원활한 사용자 인터페이스를 제공합니다.
  3. 표준 기술 기반: Ajax는 HTML, CSS, JavaScript, XML(현재는 JSON으로 대체됨)과 같은 표준 웹 기술을 사용하며 서버측 기술과는 아무런 관련이 없습니다. 이를 통해 개발자는 기존 기술과 도구를 더 쉽게 사용할 수 있습니다.
  4. 향상된 사용자 경험: Ajax를 사용하면 실시간 검색, 자동 완성, 새로 고치지 않는 양식 제출 등의 기능을 실현할 수 있어 사용자와 웹 애플리케이션 간의 상호 작용 경험이 향상됩니다.
  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는 페이지를 전환하지 않으며 모든 콘텐츠가 한 페이지에 있으므로 스타일 속성을 표시하고 값을 없음으로 설정하면 보이지 않고 높이를 차지하지 않습니다.
  2. 표시해야 하는 경우 표시 값을 차단으로 설정하세요.

넷째, 상세한 코드 완성

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. 마이아약스
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. MyAjax서비스
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. 프런트엔드 웹 코드

  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