SpringMVC详解(五)ajax+mybatis综合应用

  • Post author:
  • Post category:其他




Ajax+MyBatis+Spring练习

​ 省份列表是下拉列表框,城市名称是text文本框,添加城市和显示省份所有城市是两个按钮。用table表格显示省份的所有城市。

在这里插入图片描述



1.创建好maven的webapp项目后导入依赖



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>com.bjpowernode</groupId>
  <artifactId>ch13-work</artifactId>
  <version>1.0.0</version>
  <packaging>war</packaging>



  <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>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- jsp依赖 -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2.1-b03</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.12</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>ch13-work</finalName>
    <resources>
      <resource>
        <directory>src/main/java</directory><!--所在的目录-->
        <includes>
          <!--包括目录下的.properties,.xml 文件都会扫描到-->
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>

  </build>
</project>



2. 各种配置文件

在这里插入图片描述



2.1.Spring配置文件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: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/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--        spring配置文件:声明service,dao,工具类,事务配置-->
<!--    注解扫描器-->
    <context:component-scan base-package="com.firewolf.service"/>

    <context:property-placeholder location="classpath:conf/jdbc.properties"/>
<!--    数据源-->
    <bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

<!--    实例化mybatis的重量级对象-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        赋值-->
        <property name="dataSource" ref="dateSource"/>
        <property name="configLocation" value="classpath:conf/mybatis.xml"/>
    </bean>


    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="factory"/>
        <property name="basePackage" value="com.firewolf.dao"/>
    </bean>
</beans>



2.2.SpringMVC配置文件dispatherServlet.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: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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--    springmvc的配置文件:声明controller,视图解析器等web开发中的对象-->


    <context:component-scan base-package="com.firewolf.controller"/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!--
      作用:
       1. 创建HttpMessageConverter接口的7个实现类对象, 处理java对象到json的转换
       2. 解决静态资源中,动态资源访问失败的问题。
    -->
    <mvc:annotation-driven/>


</beans>



3.数据库用户名密码jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/springdb
jdbc.username=root
jdbc.password=123456



4.MyBatis配置文件mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--    设置日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    
    <typeAliases>
<!--        domain包中的类名就是别名-->
        <package name="com.firewolf.domain"/>
    </typeAliases>
    

    <mappers>
        <package name="com.firewolf.dao"/>
    </mappers>
</configuration>



5.web.xml (容易丢掉)

​ springmvc也是需要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">

  <!--声明spring监听器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:conf/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>


  <!--声明springmvc的中央调度器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:conf/dispatherServlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <!--声明字符集过滤器-->
  <filter>
    <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>



3.实体类

City 和Province

public class City {
    private Integer id;
    private String name;
    private Integer provinceId;
    //set and get
}

public class Province {
    private Integer id;
    private String name;
    //set and get
}



4.dao

​ 开发时先写dao层是一个明智的选择!

public interface CityDao {
    int insertCity(City city);

    List<City> selectCityByProvinceId(@Param("pid") Integer provinceid);
}

CityDao.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.firewolf.dao.CityDao">
    <!-- 使用insert,update,delete,select标签写sql语句-->
    <insert id="insertCity">
        insert into city(name,provinceid) values(#{name},#{provinceId})
    </insert>

    <select id="selectCityByProvinceId" resultType="com.firewolf.domain.City">
        select id,name,provinceId from city where provinceId=#{pid}
    </select>

</mapper>

public interface ProvinceDao {

    List<Province> selectProvinceList();

}

ProvinceDao.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.firewolf.dao.ProvinceDao">
    <!-- 使用insert,update,delete,select标签写sql语句-->
    <select id="selectProvinceList" resultType="com.firewolf.domain.Province">
        select id,name from province order by id
    </select>
</mapper>



4.Service

public interface ProvinceCityService {

    List<Province> queryAllProvince();

    int addCity(City city);

    List<City> queryCityByProvinceId(Integer provinceId);

}

package com.firewolf.service.impl;

@Service
public class ProvinceCityServiceImpl implements ProvinceCityService {
    @Resource
    private ProvinceDao pdao;
    @Resource
    private CityDao cdao;

    @Override
    public List<Province> queryAllProvince() {
        return pdao.selectProvinceList();
    }

    @Override
    public int addCity(City city) {

        int rows= cdao.insertCity(city);
        return rows;

    }

    @Override
    public List<City> queryCityByProvinceId(Integer provinceId) {


        return cdao.selectCityByProvinceId(provinceId);
    }
}



5.vo:作为前后端连接数据的工具

​ 这里新建一个CommonResult 类作为controller返回值。

package com.firewolf.vo;

public class CommonResult {

//    表示本次请求是否成功 0 :成功; 1:失败
    private Integer code;
//    错误原因
    private String msg;
//    数据
    private Object data;

    public CommonResult() {

    }

    public CommonResult(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;

    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "CommonResult{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}



6.控制器controller

package com.firewolf.controller;

import com.firewolf.domain.City;
import com.firewolf.domain.Province;
import com.firewolf.service.ProvinceCityService;
import com.firewolf.vo.CommonResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class ProvinceCityController {
    @Resource
    private ProvinceCityService service;


    /**
     * 查询所有的省份
     * */
    @RequestMapping("/queryProvince.do")
    @ResponseBody
    public CommonResult queryProvinces(){
        /**
         * 通常不用 List<Province> 因为可能是空值
         * 这里新建一个CommonResult 类作为返回值
         * */
        List<Province> list = service.queryAllProvince();

        CommonResult cr  = new CommonResult(1,"查询没有结果","");

        if(list!=null && list.size()>0){
            cr = new CommonResult(0,"查询成功",list);
        }

        return cr;
    }

    /**
     * 添加城市
     * */
    @RequestMapping("/city/addCity.do")
    @ResponseBody
    public CommonResult addCity(City city){
        int rows = service.addCity(city);
        CommonResult cr = new CommonResult();
        if(rows>0){
            cr.setCode(0);
            cr.setMsg("添加城市"+city.getName()+"成功");
            cr.setData(city);
        }else {
            cr.setCode(1);
            cr.setMsg("添加城市失败");
            cr.setData("");
        }
        return cr;
    }

    /**
     * 查询城市
     * */
    @RequestMapping("/city/queryCity.do")
    @ResponseBody
    public CommonResult queryCity(Integer pid){
        List<City> cityList = service.queryCityByProvinceId(pid);
        CommonResult cr = new CommonResult();
        if(cityList!=null && cityList.size()>0){
            cr.setCode(0);
            cr.setMsg("查询出"+cityList.size()+"个城市");
            cr.setData(cityList);
        }else {
            cr.setCode(1);
            cr.setMsg("查询无结果");
            cr.setData("");
        }
        return cr;
    }
}



7. 页面index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme() + "://" + request.getServerName()
            + ":" + request.getServerPort() + request.getContextPath() + "/";

%>
<html>
<head>
    <title>首页-练习</title>
    <base href="<%=basePath%>">
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
    <script type="text/javascript">
        $(function () {
        //    添加省份的select组件
            getProvinceList();
        //    查询按钮的单击事件
            $("#queryCity").click(function () {
                //选中的下拉列表
                var pid = $("#province>option:selected").val();
                $.get("city/queryCity.do",{pid:pid},
                    function (resp) {
                        if(resp.code==0){
                            //在后台传递code==0代表查询成功
                            alert(resp.msg);
                            $("#cityInfo").empty();
                            $.each(resp.data,function (i,n) {
                                $("#cityInfo").append("<tr><td>"+n.id+"</td><td>"+n.name+"</td></tr>");
                            })
                        }else {
                            alert(resp.msg);
                        }
                    },
                    "json")
            })

        //    添加城市
            $("#addCity").on("click",function () {
                var pid = $("#province>option:selected").val();
                var name = $(":text").val();

                $.post("city/addCity.do",{name:name,provinceId:pid},
                       function (resp) {
                         if (resp.code ==0){
                         //    连接到查询业务,或者查看城市列表的其他页面
                             alert(resp.msg);
                         }else {
                         //    重新添加数据
                             alert(resp.msg);
                         }
                       },
                    "json"
                )
            })

        })

        function getProvinceList() {
            $.ajax({
                url:"queryProvince.do",
                dataType:"json",
                success:function (resp) {
                    $("#province").empty();
                    $.each(resp.data,function (i,n) {
                        $("#province").append("<option value='"+n.id+"'>"+n.name+"</option>");
                    })
                }
            })
        }
    </script>

</head>
<body>
    <div align="center">
        <table>
            <tr>
                <td>省份列表:</td>
                <td>
                    <select id="province">
                        <option value="0">请选择...</option>
                    </select>
                </td>
            </tr>

            <tr>
                <td>城市名称</td>
                <td><input type="text" id="cityname"></td>
            </tr>

            <tr>
                <td>
                    <input type="button" id="addCity" value="添加城市">
                </td>
                <td>
                    <input type="button" id="queryCity" value="查询省份的城市">
                </td>
            </tr>

        </table>

        <div id="dataDiv">
            <table border="1">
                <thead>
                <tr>
                    <td>城市id</td>
                    <td>城市名称</td>
                </tr>
                </thead>
                <tbody id="cityInfo">

                </tbody>
            </table>
        </div>
    </div>

</body>
</html>

在这里插入图片描述



版权声明:本文为gao1213977085原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。