基于SSM的完整增删改查


idea+maven搭建 基于SSM的一套增删改查 AJAX局部刷新

SSM是基于Spring+Springmvc+Mybatis 三个框架的整合, 也是现在流行 也常用的企业级框架。

Spring :分为IOC和AOP两大主要功能来支撑Spring 它就像一个配置bean的大集合 核心是IOC(控制反转) 就是不需要去 new 建一个对象 而是Spring完成。而AOP是一些周边功能,事务的一些启用。

SpringMvc : 一个业务逻辑层 用于拦截用户的请求 跳转

Mybatis : 持久层 对JDBC的封装 用于增删改查操作

第一次写博客 可能有许多小毛病 路过的小伙伴看到无妨点评出来
下面进入正题

因为我们项目的idea +maven 搭建 先来看看整体环境是什么样的

在这里插入图片描述
可能有许多小伙伴 搭建项目时发现自己建包时只有 Directory 需要去Moudels 里面声明此包

步骤如下 打开File >Modules>在这里插入图片描述需要package的地方就声明蓝色Sources 放资源文件(XML) 就声明为Resources

搭建好相应的包后 就开始整合一下我们的所有XML文件 放在咱们相应 Resources文件夹里

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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/cache"
       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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
    <!-- Spring的配置文件  主要配置一些和 业务逻辑有关的 -->
    <!--    业务逻辑 以及组件的扫描-->
    <context:component-scan base-package="cn.xiaohe">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--        数据源 事务控制-->
    <context:property-placeholder location="classpath:dbConfig.properties"></context:property-placeholder>

    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.name}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--  ================================================  配置和Mybatis的整合 -->
    <!-- 3.配置SqlSessionFactory对象 -->
    <bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--     指定mybatis全局配置文件的位置 -->
        <property name="configLocation" value="classpath:Mybatis-Config.xml"></property>
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="pooledDataSource"></property>
        <!--      指定mybatis  mapper包下的xml文件 -->
        <property name="mapperLocations" value="classpath:Mapper/*.xml"></property>
    </bean>
    <!--      配置扫描器  将mybatis的实现加入到ioc容器中 -->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--      扫描所有dao接口的实现 加入到ioc容器中-->
        <property name="basePackage" value="cn.xiaohe.dao"></property>
    </bean>
</beans>

下面是Mybatis-config.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>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true" />

        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
        <!-- 打印查询语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>
    <plugins>
        <plugin  interceptor = "com.github.pagehelper.PageInterceptor" >
        </plugin>
    </plugins>

</configuration>

下面是Springmvc 的一些配置:

<?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:p="http://www.springframework.org/schema/p"
       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
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--       SpringMVC 的文件配置 包括一些网站跳转 逻辑跳转-->
    <context:component-scan base-package="cn.xiaohe"></context:component-scan>
<!--        配置视图解析器 用于返回-->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
        <!--    两个配置标准-->
        <!--    将springmvc不能处理的请求交给Tomcat-->
        <mvc:default-servlet-handler/>
        <!--    能支持springmvc一些更加高级的功能  比如 快捷的ajax请求 来映射动态请求-->
        <mvc:annotation-driven></mvc:annotation-driven>
    </beans>

了解过Web的朋友应该知道 启动Tomcat 运行项目第一步是会走Web.xml
必然 咱们就需要把前面需要的XML配置文件 放到Web.xml中 让这个SSM
项目能成功的跑起来

下面就是Web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <!--  启动Spring的容器  -->
  <!--web.xml的作用其实就是启动servlet的时候加载所需要的一些xml文件-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:ApplicationContext.xml</param-value>
  </context-param>

  <!--字符编码控制器 -->
  <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>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--Spring mvc的前端控制器 拦截所有请求  -->
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--初始化参数-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!--文件路径-->
    <param-value>classpath:Spring-mvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <!--默认匹配所有的请求-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

还有关于数据库连接的一个properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmday1?useUnicode=true&characterEncoding=utf8
jdbc.name=root
jdbc.password=hzy
# 最小连接数
minIdle=45
# 最大连接数
maxIdle=50
# 连接大小
initialSize=5
# 最大活跃数
maxActive=100
# 最大等待时间
maxWait=100

我们的是Maven项目所以需要在pom.xml中放入我们SSM需要的依赖

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.web</groupId>
  <artifactId>ssm</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>ssm Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>
    <!-- 设置项目编码编码 -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <!-- spring版本号 -->
    <spring.version>4.3.5.RELEASE</spring.version>
    <!-- mybatis版本号 -->
    <mybatis.version>3.4.1</mybatis.version>
  </properties>

  <dependencies>

    <!-- java ee -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>

    <!-- 单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!-- 实现slf4j接口并整合 -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- JSON -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.7</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
    <!-- mybatis 逆向工程  -->
    <dependency>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-core</artifactId>
      <version>1.3.5</version>
    </dependency>


    <!-- 数据库 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.41</version>
      <scope>runtime</scope>
    </dependency>

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

    <!-- MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>

    <!-- mybatis/spring整合包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.2</version>
    </dependency>

    <!-- Spring 单元测试 -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
    </dependency>

    <!-- JSTL -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>2.2.2</version>
    </dependency>
    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>ssm</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
      </plugin>
    </plugins>

  </build>

</project>

如果还需要有别的Jar的话 进入直接搜索即可
Maven依赖网址 点击进入

上面咱们SSM的环境就搭建完成了 照我的这个方式来的话 应该是没有问题的

接下里就开始写代码了

万变不离其宗 先开始编写咱们需要的实体类 创建到咱们的entity包里头
给它搞里头

咱们是一个两表的 所以需要用到级联属性
private address address;

package cn.xiaohe.entity;

/**
 * 实体类
 */
public class Message {
    private int id;
    private int districtId;
    private String monitorTime;
    private int pm10;

    public int getId() {
        return id;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", districtId=" + districtId +
                ", monitorTime='" + monitorTime + '\'' +
                ", pm10=" + pm10 +
                ", pm25=" + pm25 +
                ", monitoringStation='" + monitoringStation + '\'' +
                ", last_modifyTime='" + last_modifyTime + '\'' +
                ", address=" + address +
                '}';
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getDistrictId() {
        return districtId;
    }

    public void setDistrictId(int districtId) {
        this.districtId = districtId;
    }

    public String getMonitorTime() {
        return monitorTime;
    }

    public void setMonitorTime(String monitorTime) {
        this.monitorTime = monitorTime;
    }

    public int getPm10() {
        return pm10;
    }

    public void setPm10(int pm10) {
        this.pm10 = pm10;
    }

    public int getPm25() {
        return pm25;
    }

    public void setPm25(int pm25) {
        this.pm25 = pm25;
    }

    public String getMonitoringStation() {
        return monitoringStation;
    }

    public void setMonitoringStation(String monitoringStation) {
        this.monitoringStation = monitoringStation;
    }

    public String getLast_modifyTime() {
        return last_modifyTime;
    }

    public void setLast_modifyTime(String last_modifyTime) {
        this.last_modifyTime = last_modifyTime;
    }

    public cn.xiaohe.entity.address getAddress() {
        return address;
    }

    public void setAddress(cn.xiaohe.entity.address address) {
        this.address = address;
    }

    private int pm25;
    private String monitoringStation;
    private String last_modifyTime;
    private address address;


}

第二个实体

package cn.xiaohe.entity;

import java.util.List;

/**
 * 实体类
 */
public class address {
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private int id;
    private String name;

    public List<Message> getMessages() {
        return messages;
    }

    public void setMessages(List<Message> messages) {
        this.messages = messages;
    }

    private List<Message> messages;
}

下面再来编写咱们的方法 放dao层包里
给他搞里头!!
创建mangerMapper 一个接口

package cn.xiaohe.dao;

import cn.xiaohe.entity.Message;

import java.util.List;

public interface mangerMapper {

    List<Message> findAll();

    int delete(int id);

    int add(Message message);

    Message GetMessage(int id);

    int Update(Message message);
}

创建addressMapper一个接口

package cn.xiaohe.dao;

import cn.xiaohe.entity.address;

import java.util.List;

public interface addressMapper {
    //查询全部部门
    public List<address> findAll();
}

然后编写咱们的Service 业务层
和dao接口一样的方法 创建两个一样的 接口 命名为xxxxService


    package cn.xiaohe.Service;

import cn.xiaohe.entity.Message;

import java.util.List;

/**
 * service是业务层,是使用一个或多个模型执行操作的方法。
 * 1. 封装通用的业务逻辑,操作。
 * 如一些数据的检验,可以通用处理。
 * 2. 与数据层的交互。
 * 3. 其他请求:如远程服务获取数据,如第三方api等。
 */
public interface mangerService {
    
        List<Message> findAll();

        int delete(int id);

        int add(Message message);

        Message GetMessage(int id);

        int Update(Message message);

}


第二个 xxxService

package cn.xiaohe.Service;

import cn.xiaohe.entity.address;

import java.util.List;

public interface addressService {
    //查询全部部门
    public List<address> findAll();
}

然后咱们在前面的目录中看见了Service下有个Service impl包
固然 就是继承Service 实现里面的方法
在Service impl 下建立 xxxServiceimpl.class
如下

关于一些

package cn.xiaohe.Service.impl;

import cn.xiaohe.Service.mangerService;
import cn.xiaohe.dao.mangerMapper;
import cn.xiaohe.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 如果一个类带了@Service注解,将自动注册到Spring容器,不需要再在applicationContext.xml
 * 文件定义bean了,类似的还包括@Component、@Repository、@Controller。
 */
@Service
public class mangerServiceimpl implements mangerService {


    /**
     * @Autowired是用在JavaBean中的注解,
     * 通过byType形式,用来给指定的字段或方法注入所需的外部资源。
     */
    @Autowired
    private mangerMapper mangerMapper;

    public List<Message> findAll() {

        return mangerMapper.findAll();
    }

    public int delete(int id) {

        return mangerMapper.delete(id);
    }

    public int add(Message message) {

        return mangerMapper.add(message);
    }

    public Message GetMessage(int id) {

        return mangerMapper.GetMessage(id);
    }

    public int Update(Message message) {

        return mangerMapper.Update(message);
    }
}

下面是Mybatis框架要做的 在Rescources下建立Mapper包
在包下 建立需要的XML 文件(SQL映射文件)
下面上代码

<?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="cn.xiaohe.dao.mangerMapper">
<!--
List<Message> findAll();
-->
    <resultMap id="resmap" type="cn.xiaohe.entity.Message" autoMapping="true">
    <id property="id" column="id"></id>
        <association property="address"  javaType="cn.xiaohe.entity.address" autoMapping="true">
            <id property="id" column="id"></id>
        </association>
    </resultMap>

    <select id="findAll" resultType="cn.xiaohe.entity.Message" resultMap="resmap">
    select a.id,d.`name`,a.monitor_time,a.pm10,a.pm25,a.monitoring_station
from air_quality_time a LEFT JOIN district d
on a.district_id=d.id
    </select>

<!--
int delete(int id);
-->
    <delete id="delete">
    delete from air_quality_time
    where id=#{id}
    </delete>
<!--
int add(Message message);
-->
   <insert id="add">
INSERT INTO `ssmday1`.`air_quality_time`(`district_id`,`monitor_time`,`pm10`, `pm25`,`monitoring_station`)
 VALUES (#{districtId},#{monitorTime}, #{pm10}, #{pm25},#{monitoringStation});
   </insert>

<!--
 Message GetMessage(int id);
-->
    <select id="GetMessage" resultType="cn.xiaohe.entity.Message">
select d.`name`,a.`monitor_time`,a.pm10,a.pm25,a.monitoring_station,a.district_id
from air_quality_time a,district d
where a.district_id=d.id and a.id=#{id}
    </select>

<!--
 int Update(Message message);
-->
<update id="Update">
    UPDATE `ssmday1`.`air_quality_time`
    SET `district_id` = #{districtId}, `monitor_time` =#{monitorTime}, `pm10` = #{pm10}, `pm25` = #{pm25}, `monitoring_station` = #{monitoringStation}
    WHERE `id` = #{id};
</update>

</mapper>

第二个XML(SQL映射文件)

<?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="cn.xiaohe.dao.addressMapper">
    <!--
    public List<address> findAll();
    -->
    <select id="findAll" resultType="cn.xiaohe.entity.address">
    SELECT * FROM `district`
    </select>
</mapper>

后台最后一步SpringMvc控制层 Controller

package cn.xiaohe.controller;

import cn.xiaohe.Service.impl.mangerServiceimpl;
import cn.xiaohe.Util.Msg;
import cn.xiaohe.entity.Message;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *      逻辑控制层
 */

/**
 * @RequestMapping
 * 是一个用来处理请求地址映射的注解,可用于类或方法上。
 * 用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
 */
@Controller
public class mangerController {
    //自动装配
    @Autowired
    private mangerServiceimpl mangerServiceimpl;
    //前端AJAX 返回的路径
    @RequestMapping(value = "/views/getJSON")
    //返回JSON 格式
    @ResponseBody
    public Msg getJSON(@RequestParam(value = "pn",defaultValue = "1")  Integer pn){
        PageHelper.startPage(pn,5);
        List<Message> list = mangerServiceimpl.findAll();
        PageInfo page = new PageInfo(list,5);
        return Msg.success().add("pageInfo",page);
    }

    /**
     * 通过 id删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/views/delete/{id}")
    @ResponseBody
    public Msg delete(@PathVariable("id") int id){
    mangerServiceimpl.delete(id);
    return Msg.success();
    }

    /**
     * 新增
     * @param message
     * @return
     */
    @RequestMapping(value = "/views/add",method = RequestMethod.POST)
    @ResponseBody
    public Msg add(Message message){
        mangerServiceimpl.add(message);
        return Msg.success();
    }

    /**
     * 通过id查找相关信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/views/GetMessage/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Msg GetMessage(@PathVariable("id") int id){
     Message message=   mangerServiceimpl.GetMessage(id);
        return Msg.success().add("Mes",message);
    }

    /**
     * 修改
     * @param message
     * @return
     */
    @RequestMapping(value = "/views/update/{id}")
    @ResponseBody
    public Msg update(Message message){
        mangerServiceimpl.Update(message);
        return Msg.success();
    }
}

第二个Controller

package cn.xiaohe.controller;

import cn.xiaohe.Service.impl.addressServiceimpl;
import cn.xiaohe.Util.Msg;
import cn.xiaohe.entity.address;
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
public class addressContrller {
    @Autowired
    private addressServiceimpl addressServiceimpl;

    @RequestMapping(value = "/views/findAll")
    @ResponseBody
    public Msg findAll(){
     List<address> list= addressServiceimpl.findAll();
     return Msg.success().add("pageinfo",list);
    }
}

这边我们后端的操作就完成了 可以通过@RequstMapping里的地址来访问一下有没有数据
比如(http://localhost:8080/MembersInformation/findAll)最后的名字便是你@RequstMapping里的命名
到了最后的前端 我们是用的AJAX来实现的增删改查操作 页面无刷新 增强用户体验
前端代码里面注释就不一一打出来了
直接扣吧 兄弟们
index.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.1.min.js"></script>
<script src="https://code.jquery.com/jquery-2.0.0.min.js"></script>
<script src="jquery-1.8.3.js"></script>
<html>
<body>
<head>
    <style type="text/css">
        table
        {
            border-collapse: collapse;
            margin: 0 auto;
            text-align: center;
        }
        table td, table th
        {
            border: 1px solid #cad9ea;
            color: #666;
            height: 30px;
        }
        table thead th
        {
            background-color: #CCE8EB;
            width: 100px;
        }
        table tr:nth-child(odd)
        {
            background: #fff;
        }
        table tr:nth-child(even)
        {
            background: #F5FAFA;
        }
    </style>
    <%
        pageContext.setAttribute("APP_PATH",request.getContextPath());
    %>
</head>

<table align="center" border="1">
    <h2 align="center">雨水测量系统</h2>
    <h4><a href="add.jsp">新增信息</a></h4>
    <thead>
<tr>
    <td>序号</td>
    <td>区域</td>
    <td>检测时间</td>
    <td>PM10数据</td>
    <td>PM2.5数据</td>
    <td>检测站</td>
    <td>操作</td>
</tr>
    </thead>
    <tbody>
    <tr>

    </tr>
    </tbody>
    </table>

    <%-- 显示分页信息 --%>
    <div class="row">
        <%--    分页文字信息--%>
        <div class="col-md-6" id="page"></div>

        <%--    分页码数信息--%>
        <div class="col-md-6" id="page_nav_area">

        </div>

    </div>
    <script>
$(function () {
    topage(1);
})
    function table(result) {
        $("tbody tr").empty();
        var user = result.extend.pageInfo.list;
        $.each(user,function (index,item) {
            var uls = $("<tr><tr>");
            var id = $("<td></td>").append(item.id);
            var name = $("<td></td>").append(item.address.name);
            var  monitorTime= $("<td></td>").append(item.monitorTime);
            var pm10 = $("<td></td>").append(item.pm10);
            var pm25 = $("<td></td>").append(item.pm25);
            var pm25 = $("<td></td>").append(item.pm25);
            var monitoringStation = $("<td></td>").append(item.monitoringStation);
            var bj = $("<td><button class='delete'>删除</button><button class='update'>编辑</button></td>")
            $("<TR></TR>").append(id).append(name).append(monitorTime).append(pm10).append(pm25).append(monitoringStation).append(bj).appendTo("tbody");
        })

        $(".delete").click(function () {
            var id = $(this).parents("tr").find("td:eq(0)").text();
            if (confirm("确定删除编号为"+id+"的信息吗")){
                $.ajax({
                    url:"${APP_PATH}/views/delete/"+id,
                    type:"DELETE",
                    success:function () {
                        alert("删除成功");
                        topage(1);
                    }
                })
            }else {
                return false;
            }
        })
    $(".update").click(function () {
        var id = $(this).parents("tr").find("td:eq(0)").text();
        window.location.href = "update.jsp?id="+id;
    })

    }
    function topage(pn) {
        $.ajax({
            url: "${APP_PATH}/views/getJSON",
            data: "pn=" +pn,
            type:"GET",
            success:function (result) {
                table(result);
            }
        })
    }

    </script>
</table>
</body>
</html>

新增 add.jsp页面

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2019/8/21
  Time: 17:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <script src="jquery-1.8.3.js"></script>
    <script src="jq.js"></script>
    <%
        pageContext.setAttribute("APP_PATH",request.getContextPath());
    %>
</head>
<body>
<form id="dd">
        <div align="center">
            <input type="hidden" id="ids" value="<%=request.getParameter("id") %>">
            监测区域:<select id="address" name="districtId"></select><br>
            检测日期:<input id="date" type="text" name="monitorTime"><br>
            PM10值:<input id="pm10" type="text" name="pm10"><br>
            PM2.5值:<input id="pm25" type="text" name="pm25"><br>
            检测站:<input id="zhan" type="text" name="monitoringStation"><br>
            <input type="button" value="保存" id="add"><input type="button" value="清空">
        </div>
</form>
<script>

    //加载读取下拉框数据
    $(function () {
        $.ajax({
            url:"${APP_PATH}/views/findAll",
            type:"GET",
            success:function (result) {
                $.each(result.extend.pageinfo,function () {
                    var option = $("<option value='"+this.id+"'>"+this.name+"</option>")
                    option.appendTo("#address");
                });
            }
        })
    })


    $("#add").click(function () {
        $.ajax({
            url:"${APP_PATH}/views/add",
            type:"POST",
            data:$("#dd").serialize(),
            success:function (result) {
                console.log(result)
                alert("OK");
                location.href="index.jsp";
            }
        })
    })

</script>

</body>
</html>

在前面的目录可以看到我还用了个Util工具类
给大家吧 我Msg里面写了一个Map
返回的就是一个map集合

package cn.xiaohe.Util;

import java.util.HashMap;
import java.util.Map;

public class Msg {
    //返回状态码
    private int Code;

    public int getCode() {
        return Code;
    }

    public void setCode(int code) {
        Code = code;
    }

    public String getMsg() {
        return msg;
    }

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

    //提示信息
    private String msg;

    //用户要返回给浏览器的数据
    private  Map<String,Object> extend = new HashMap<String, Object>();

    public  static Msg success(){
        Msg result = new Msg();
        result.setCode(100);
        result.setMsg("OK");
        return result;
    }

    public Map<String, Object> getExtend() {
        return extend;
    }

    public void setExtend(Map<String, Object> extend) {
        this.extend = extend;
    }

    public  static Msg fail(){
        Msg result = new Msg();
        result.setCode(200);
        result.setMsg("fail");
        return result;
    }

    public Msg add(String key, Object value){
            this.getExtend().put(key,value);
            return this;
    }

}

最后把我的mysql数据库的表也放来吧
在这里插入图片描述
关于SSM搭建环境以及增删改查的操作就在这里插入图片描述
命名和实体类尽量一样哦

SSM的环境搭建 以及增删改查的基本操作都在这儿了 有任何问题可以发到我邮箱 2010944641@qq.com 源码已发

  • 9
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
SSM框架是指Spring+SpringMVC+MyBatis三大框架的整合,下面提供一个基于SSM框架的增删页面示例: 首先,我们需要在SpringMVC的配置文件中添加视图解析器和处理器映射器: ```xml <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 处理器映射器 --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" /> <!-- 处理器适配器 --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> ``` 然后,我们需要编写一个Controller类来处理页面请求,并且调用Service层来实现增删的操作: ```java @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/list", method = RequestMethod.GET) public ModelAndView userList() { ModelAndView modelAndView = new ModelAndView("userList"); List<User> userList = userService.findAllUsers(); modelAndView.addObject("userList", userList); return modelAndView; } @RequestMapping(value = "/add", method = RequestMethod.GET) public ModelAndView addUserPage() { ModelAndView modelAndView = new ModelAndView("addUser"); return modelAndView; } @RequestMapping(value = "/add", method = RequestMethod.POST) public ModelAndView addUser(User user) { ModelAndView modelAndView = new ModelAndView("redirect:/user/list"); userService.addUser(user); return modelAndView; } @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) public ModelAndView deleteUser(@PathVariable("id") int id) { ModelAndView modelAndView = new ModelAndView("redirect:/user/list"); userService.deleteUser(id); return modelAndView; } @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) public ModelAndView updateUserPage(@PathVariable("id") int id) { ModelAndView modelAndView = new ModelAndView("updateUser"); User user = userService.findUserById(id); modelAndView.addObject("user", user); return modelAndView; } @RequestMapping(value = "/update", method = RequestMethod.POST) public ModelAndView updateUser(User user) { ModelAndView modelAndView = new ModelAndView("redirect:/user/list"); userService.updateUser(user); return modelAndView; } } ``` 在以上Controller类的代码中,我们提供了五个请求方法: 1. `userList()`:用于展示所有用户信息的页面; 2. `addUserPage()`:用于展示添加用户信息的页面; 3. `addUser(User user)`:用于接收添加用户信息的表单数据; 4. `deleteUser(int id)`:用于删除指定用户信息; 5. `updateUserPage(int id)`:用于展示修指定用户信息的页面; 6. `updateUser(User user)`:用于接收修用户信息的表单数据。 最后,我们需要编写相应的JSP页面来展示数据和表单。比如我们可以编写一个userList.jsp页面来展示所有用户信息: ```html <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>User List</title> </head> <body> <h1>User List</h1> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Gender</th> <th>Phone</th> <th>Email</th> <th>Action</th> </tr> </thead> <tbody> <c:forEach items="${userList}" var="user"> <tr> <td>${user.id}</td> <td>${user.name}</td> <td>${user.age}</td> <td>${user.gender}</td> <td>${user.phone}</td> <td>${user.email}</td> <td> <a href="<c:url value='/user/update/${user.id}'/>">Edit</a> <a href="<c:url value='/user/delete/${user.id}'/>">Delete</a> </td> </tr> </c:forEach> </tbody> </table> <a href="<c:url value='/user/add'/>">Add User</a> </body> </html> ``` 在以上JSP页面的代码中,我们使用了JSTL标签库来遍历所有用户信息,并且提供了“Add User”、“Edit”和“Delete”三个超链接来触发相关请求方法。 其他的JSP页面也类似,只需要根据表单数据的不同来进行相应的处理即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值