簡單易懂的SSM整合:商城小專案001(設定SSM環境+查詢所有操作+新增操作)

2020-10-14 11:00:31

(1)dao、service都由Spring容器構架(applicationContext.xml)
(2)controller由SpringMVC容器構建(springmvc-servlet.xml)

1.設定pom依賴

<?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>1012_2_ssm</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <spring.version>4.3.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</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-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.7</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>


</project>

2.web.xml:設定Spring+filter亂碼+SpringMVC

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>
    <context-param>
        <param-name>contextConfigLocation</param-name>
    <param-value>classpath:application.xml</param-value>
</context-param>

    <!--3.處理亂碼-->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--整合ssm-->
    <!--1.spring容器的監聽器
    spring.xml
    -->

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

    <!--2.springmvc的設定
       springmvc.xml
   -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

3.建立實體entity層+mapper層(dao)

在這裡插入圖片描述

package entity;

import lombok.Data;

import java.math.BigDecimal;
import java.util.Date;

/**
 * zt
 * 2020/10/12
 * 15:19
 */
@Data
public class Product {
    private int pid;
    private int tid;
    private String pname;
    private Date ptime;
    private String pinfo;
    private BigDecimal pprice;
    private int pstate;
    private String pimage;
}

package mapper;

import entity.Product;

import java.util.List;

/**
 * zt
 * 2020/10/12
 * 15:22
 */
public interface ProductMapper {
    public List<Product> findAll();
    public Product findById(int id);
    public int update(Product product);
    public int add(Product product);
}

4.為mapper層(dao)建立對應的mapper檔案(裡面寫增刪改查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="mapper.ProductMapper">



    <!--private int pid;
    private int tid;
    private String pname;
    private Date ptime;
    private String pinfo;
    private BigDecimal pprice;
    private int pstate;
    private String pimage;-->

    <sql id="mysql">
        p_id as pid,t_id as tid,p_name as pname,p_time as ptime,p_info as pinfo,p_price as pprice,
        p_state as pstate,p_image as pimage
    </sql>
    <!-- public List<Product> findAll();
    public Product findByid(int id);
    public int update(Product product);
    public int add(Product product);-->
    <select id="findAll" resultType="entity.Product">
        select <include refid="mysql"></include>
        from product
    </select>
    <select id="findByid" resultType="entity.Product">
        select <include refid="mysql"></include>
        from product where p_id = #{id}
    </select>
    <update id="update" parameterType="entity.Product">
        update product
        <set>
            <if test="pname!=null pname!=''">
                p_name=#{pname},
            </if>
            <if test="pinfo!=null pinfo!=''">
                p_info=#{pinfo},
            </if>
            <if test="pprice!=null">
                p_price=#{pprice},
            </if>
        </set>
        where p_id = #{pid}
    </update>
    <insert id="add" parameterType="entity.Product">
        insert into product(t_id,p_name,p_info,p_price,p_image,p_state,p_time)
        value(#{tid},#{pname},#{pinfo},#{pprice},#{pimage},#{pstate},#{ptime})
    </insert>

</mapper>

5.service層

其中ProductServiceImpl引入dao,使用註解@Resource注入,將dao從spring容器中引入
在這裡插入圖片描述

package service;

import entity.Product;

import java.util.List;

/**
 * zt
 * 2020/10/12
 * 15:35
 */
public interface ProductService {
    public List<Product> findAll();
    public Product findByid(int id);
    public int update(Product product);
    public int add(Product product);
}

package service.impl;

import entity.Product;
import mapper.ProductMapper;
import org.springframework.stereotype.Service;
import service.ProductService;

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

/**
 * zt
 * 2020/10/12
 * 15:36
 */
@Service("productServiceImpl")
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductMapper productMapper;

    @Override
    public List<Product> findAll() {

        return productMapper.findAll();
    }

    @Override
    public Product findByid(int id) {
        return productMapper.findById(id);
    }

    @Override
    public int update(Product product) {
        return productMapper.update(product);
    }

    @Override
    public int add(Product product) {
        return productMapper.add(product);
    }
}

6.建立controller

自動注入ProductService
在這裡插入圖片描述

package controller;


import entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.ProductService;
import utils.R;

import java.util.*;

/**
 * zt
 * 2020/10/12
 * 15:39
 */
@Controller
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @RequestMapping("/findAll")
    @ResponseBody
    public List<Product> findAll(){
        return productService.findAll();
    }

    @RequestMapping("/add")
    @ResponseBody
    public R add(@RequestBody Product product){
        product.setTid(1);
        product.setPtime(new Date());
//        System.out.println(product.toString());
        int i =  productService.add(product);
        if (i>0){
            return R.ok("新增成功");
        }
        return R.error("新增失敗");
    }
}

7.spring的組態檔applicationContext.xml

在這裡插入圖片描述

1.載入properties

2.設定SqlSessionFactory

3.構建mapper

4.構建service(包掃描)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <context:property-placeholder location="classpath:dbinfo.properties"></context:property-placeholder>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

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

    <context:component-scan base-package="service"></context:component-scan>
</beans>

資料庫設定dbinfo.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///myshop?characterEncoding=utf-8
#不要直接命名username  不然衝突了
jdbc.username=root
#m預設spring內部已經存在username=你電腦的主機名的一個鍵值對
jdbc.password=root

8.SpringMVC設定springmvc-servlet.xml

包掃描+註解驅動+靜態資源放行

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <context:component-scan base-package="controller"></context:component-scan>

    <mvc:annotation-driven></mvc:annotation-driven>

    <mvc:default-servlet-handler></mvc:default-servlet-handler>

</beans>

9.頁面

在這裡插入圖片描述
index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="static/css/bootstrap.min.css" rel="stylesheet">
    <link href="static/bootstrap-table/bootstrap-table.css">
    <script type="text/javascript" src="static/js/jquery-2.2.4.js"></script>
    <script type="text/javascript" src="static/bootstrap-table/bootstrap-table.js"></script>
</head>
<body>

<div id="toolbar">
    <button class="btn btn-success" id="addBtn">新增</button>
    <!--<button class="btn btn-success" id="addBtn1">新增</button>
    <button class="btn btn-success" id="addBtn2">新增</button>-->
</div>


<table id="table">
</table>
<script type="text/javascript">
    $(function(){
        $("#table").bootstrapTable({
                url:'/product/findAll',//請求地址
                pagination:true, //分頁  預設前端分頁
                search:true,
                toolbar:"#toobar",
                columns: [[//field:"pid"  把伺服器端響應的json,key為pid的欄位渲染到該列
                    //每個{}  對應  一列,field:"pid" json的key,title:"編號" 列的標題
                    {field:"pid",title:"編號", align: 'center', valign: 'middle'},
                    {field:"pname",title:"商品名稱"},
                    {field:"pprice",title:"商品價格"},
                    {field:"pinfo",title:"商品資訊"},
                    {field:"ptime",title:"上架時間"},
                    {field:"ptime",title:"修改"}
                ]]
        });

        $("#addBtn").click(function () {
            location.href="add.html";
        })
    });
</script>
</body>
</html>

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>add</title>
    <link href="static/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="static/js/jquery-2.2.4.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btn").click(function () {
            var d = {"pname":$("#pname").val(),"pprice":$("#pprice").val(),"pinfo":$("#pinfo").val()};
            $.ajax({
                url:'/product/add',//請求地址
                type:"post",
                data:JSON.stringify(d),
                dataType:"json",
                contentType:"application/json",
                success:function (r) {
                    if(r.code===1){
                        location.href="index.html";
                    }else{
                        alert(r.msg);
                    }
                }
            })
        })
    })
</script>
</head>

<body>
    <h1>新增頁面</h1>
    <form class="form-inline">
        <div class="form-group" style="width: 200px">
            <label for="pname">商品名稱</label>
            <input class="form-control" id="pname">
        </div>
        <div class="form-group" style="width: 200px">
            <label for="pprice">價格</label>
            <input class="form-control" id="pprice" type="text">
        </div>
        <div class="form-group" style="width: 200px">
            <label for="pinfo">商品資訊</label>
            <input class="form-control" id="pinfo" type="text">
        </div>
    </form>
    <button type="button" class="btn-success" id="btn">新增</button>
</body>
</html>

10.執行結果

在這裡插入圖片描述