SSM整合:商城小项目001(配置SSM环境+查询所有操作+添加操作)

时间:2022-07-28
本文章向大家介绍SSM整合:商城小项目001(配置SSM环境+查询所有操作+添加操作),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

(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 () {
            kk="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){
                        kk="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.运行结果