SSM结合AJAX实现无刷新数据交互

目录

代码:

pom.xml配置

spring的配置bean.xml

springmvc的配置springmvc.xml

web层配置web.xml

前端js

前端html

后端处理器


ajax异步无刷新技术

效果:

代码:
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>book-ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>book-ssm Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.1.16.RELEASE</spring.version>
  </properties>

  <dependencies>
    <!--spring的相关配置-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--跟web整合的-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--跟测试整合-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--跟mybatis整合的-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!---->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>

    <!--日志-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.36</version>
    </dependency>
<!--    <dependency>-->
<!--      <groupId>log4j</groupId>-->
<!--      <artifactId>log4j</artifactId>-->
<!--      <version>1.2.17</version>-->
<!--    </dependency>-->
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.10</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>

    <!--数据库-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.26</version>
    </dependency>

    <!--连接池-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.12</version>
    </dependency>

    <!--测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.14.2</version>
    </dependency>

    <!--分页依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.3.2</version>
    </dependency>
  </dependencies>


  <build>
    <finalName>book-ssm</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>
spring的配置bean.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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">


    <context:property-placeholder file-encoding="UTF-8" location="classpath:db.properties"/>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
        <property name="minPoolSize" value="${jdbc.minPoolSize}"/>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
    </bean>


    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"/>
        <!--使用了别名 如com.fs.book.entity.Book  只需要写Book就可以了-->
        <property name="typeAliasesPackage" value="com.fs.book.entity"/>
        <!--使用 spring 的属性配置方式,拦截器插件-->
        <property name="plugins" >
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <!--使用下面的方式配置参数,一行配置一个 -->
                        <props>
                            <prop key="helperDialect">mysql</prop>
                            <prop key="reasonable">true</prop>
                        </props>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.fs.book.mapper"/>
    </bean>

    <context:component-scan base-package="com.fs.book"/>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!--声明式 事务基于注解方式配置  事务注解驱动 -->
    <tx:annotation-driven/>

    <!--扫描注解-->
    <context:component-scan base-package="com.fs.book.service,com.fs.book.util"/>
</beans>
springmvc的配置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:mvc="http://www.springframework.org/schema/mvc"
       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/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">


    <!--mvc的注解驱动-->
    <mvc:annotation-driven/>

    <!--视图解析器: 通过逻辑视图名, 找物理视图, 默认跳转方式: 转发-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--
            suffix:后缀,
            prefix:前缀
        -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--扫描controller注解-->
    <context:component-scan base-package="com.fs.book.web"/>


</beans>
web层配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--配置一个监听器,监听tomcat启动时,创建spring的IOC容器,将其保存全局域中-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--加载Spring的配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:bean.xml</param-value>
    </context-param>
    
    <!--springmvc的前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加载springmvc配置文件:
            默认加载文件:WEB-INF目录下<servlet-name>标签中内容.xml。但是一般把配置文件放在resources文件中,最终是在类路径中
            所以需要配置
        -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!--编码过滤器-->
<!--    <filter>-->
<!--        <filter-name>EncodingFilter</filter-name>-->
<!--        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>-->
<!--        <init-param>-->
<!--            <param-name>encoding</param-name>-->
<!--            <param-value>UTF-8</param-value>-->
<!--        </init-param>-->
<!--        <init-param>-->
<!--            <param-name>forceRequestEncoding</param-name>-->
<!--            <param-value>true</param-value>-->
<!--        </init-param>-->
<!--        <init-param>-->
<!--            <param-name>forceResponseEncoding</param-name>-->
<!--            <param-value>true</param-value>-->
<!--        </init-param>-->
<!--    </filter>-->
<!--    <filter-mapping>-->
<!--        <filter-name>EncodingFilter</filter-name>-->
<!--        <url-pattern>/*</url-pattern>-->
<!--    </filter-mapping>-->
</web-app>
前端js
$(function (){
    $(".publish-form .send").click(function(){
        let uname = $(".publish-form .username").val();
        let text = $(".publish-form .comments").val();
        if(uname.trim() =="" || text.trim() == ""){
            alert("内容不能为空");
            return;
        }
        let ul = $(".show ul")
        let li= $(`
        <li>
            <div class="show-top">
                <div class="photo-uname">
                    <img src="/style/blue/source/03.png" alt="">
                    <span class="uname">`+uname+`</span>
                </div>
                <div class="publish-time">`+format(new Date().getTime())+`</div>
            </div>
            <div class="comments-con">`+text+`
            </div>
        </li>`);

        $(ul).prepend(li);
        $(".publish-form .username").val("")
        $(".publish-form .comments").val("");
    })


    function format(dataString)
    {
        //dataString是整数,否则要parseInt转换
        var time = new Date(dataString);
        var year = time.getFullYear();
        var month = time.getMonth()+1;
        var day = time.getDate();
        var hour = time.getHours();
        var minute = time.getMinutes();
        var second = time.getSeconds();
        return year+'-'+(month<10?'0'+month:month)+'-'+(day<10?'0'+day:day)+' '+(hour<10?'0'+hour:hour)+':'+(minute<10?'0'+minute:minute)+':'+(second<10?'0'+second:second)
    }

    //加载更多事件
    $("#more").click(function(){
        $.ajax({
            url:"/more.do",
            datatype:"json",
            success:function (data){
                $.each(data,function(index,item){
                    let li= $(`
                        <li>
                            <div class="show-top">
                                <div class="photo-uname">
                                    <img src="/style/blue/source/`+item.imagePath+`" alt="">
                                    <span class="uname">`+item.nickName+`</span>
                                </div>
                                <div class="publish-time">`+item.sendTime+`</div>
                            </div>
                            <div class="comments-con">`+item.info+`
                            </div>
                        </li>`);
                    $(".show ul").append(li);
                })
            }
        })
    })
})
前端html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>留言板</title>
    <link rel="stylesheet" href="/style/blue/base1.css">
    <link rel="stylesheet" href="/style/blue/test.css">
</head>
<body>
<div class="container">
    <div class="publish-form">
        <h2>留言板</h2>
        <input type="text" placeholder="用户名" name="username" class="username">
        <textarea rows="5" cols="" placeholder="文明留言~" name="comments" class="comments" style="resize:none"></textarea>
        <span class="send">发送</span>
    </div>
    <div class="show">
        <ul>
            <li>
                <div class="show-top">
                    <div class="photo-uname">
                        <img src="/style/blue/source/03.png" alt="">
                        <span class="uname">顷之</span>
                    </div>
                    <div class="publish-time">2023-11-09 23:44:53</div>
                </div>
                <div class="comments-con">
                    注意保暖
                </div>
            </li>
        </ul>
        <div id="more">加载更多</div>
    </div>
</div>
<script src="/script/jquery-3.7.0.min.js"></script>
<script src="/script/test.js"></script>
</body>
</html>
后端处理器
package com.fs.book.web;

import com.fs.book.entity.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
public class TestController {
    @RequestMapping("more.do")
    @ResponseBody
    public List more(){
        Test test = new Test("野子","今天天气很好,风景也好","02.png","2023-10-27 13:11:53");
        Test test1 = new Test("妥妥干饭人","下雪了","01.png","2023-11-21 15:12:42");
        List list = new ArrayList();
        list.add(test);
        list.add(test1);
        return list;
    }
}

后端实际需要查询数据库中的数据,上面只用于演示效果。

用到jackson-databind依赖,结合@ResponseBody注解,可以把java对象转换为json字符串

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值