使用SSM的xml和注解两种方式完成一个完整的增删改查案例

ssm整合整理

1.ssm整合项目工程结构

在这里插入图片描述
在这里插入图片描述

整合的思路

在这里插入图片描述

2.day08_ssm_project项目(使用xml-注解)

各文件如下:

customer.sql

  -- ----------------------------
    -- Table structure for customer
    -- ----------------------------
    CREATE TABLE `customer` (
      `cust_id` int(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
      `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
      `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源',
      `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业',
      `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别',
      `cust_address` varchar(128) DEFAULT NULL COMMENT '客户联系地址',
      `cust_phone` varchar(64) DEFAULT NULL COMMENT '客户联系电话',
      `cust_create_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
      PRIMARY KEY (`cust_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of customer
    -- ----------------------------
    INSERT INTO `customer` VALUES ('1', '传智播客', '网络营销', '互联网', '普通客户', '津安创意园', '0208888887', '2020-01-03 10:09:24');
    INSERT INTO `customer` VALUES ('2', '黑马程序员', '网络营销', '互联网', '普通客户', '津安创意园', '0208888887', '2020-01-03 10:09:27');
    INSERT INTO `customer` VALUES ('3', '传智专修学院', '网络营销', '互联网', '普通客户', '津安创意园', '0208888887', '2020-01-03 10:09:31');
    INSERT INTO `customer` VALUES ('4', '华山派', '电视广告', '传统媒体', 'VIP', '津安创意园', '0208888886', '2020-01-03 10:09:33');
    INSERT INTO `customer` VALUES ('5', '武当派', '电视广告', '传统媒体', 'VIP', '津安创意园', '0208888886', '2020-01-03 10:09:37');
    INSERT INTO `customer` VALUES ('6', '丐帮', '电视广告', '传统媒体', 'VIP', '津安创意园', '0208888886', '2020-01-03 10:09:39');

Customer.java

  package com.itheima.pojo;
    
    import java.util.Date;
    
    public class Customer {
    
        //客户编号(主键)
        private Integer custId;
    
        //客户名称(公司名称)
        private String custName;
    
        //客户信息来源
        private String custSource;
    
        //客户所属行业
        private String custIndustry;
    
        //客户级别
        private String custLevel;
    
        //客户联系地址
        private String custAddress;
    
        //客户联系电话
        private String custPhone;
    
        //创建时间
        private Date custCreateTime;
    
        public Integer getCustId() {
            return custId;
        }
    
        public void setCustId(Integer custId) {
            this.custId = custId;
        }
    
        public String getCustName() {
            return custName;
        }
    
        public void setCustName(String custName) {
            this.custName = custName;
        }
    
        public String getCustSource() {
            return custSource;
        }
    
        public void setCustSource(String custSource) {
            this.custSource = custSource;
        }
    
        public String getCustIndustry() {
            return custIndustry;
        }
    
        public void setCustIndustry(String custIndustry) {
            this.custIndustry = custIndustry;
        }
    
        public String getCustLevel() {
            return custLevel;
        }
    
        public void setCustLevel(String custLevel) {
            this.custLevel = custLevel;
        }
    
        public String getCustAddress() {
            return custAddress;
        }
    
        public void setCustAddress(String custAddress) {
            this.custAddress = custAddress;
        }
    
        public String getCustPhone() {
            return custPhone;
        }
    
        public void setCustPhone(String custPhone) {
            this.custPhone = custPhone;
        }
    
        public Date getCustCreateTime() {
            return custCreateTime;
        }
    
        public void setCustCreateTime(Date custCreateTime) {
            this.custCreateTime = custCreateTime;
        }
    
        @Override
        public String toString() {
            return "Customer{" +
                    "custId=" + custId +
                    ", custName='" + custName + '\'' +
                    ", custSource='" + custSource + '\'' +
                    ", custIndustry='" + custIndustry + '\'' +
                    ", custLevel='" + custLevel + '\'' +
                    ", custAddress='" + custAddress + '\'' +
                    ", custPhone='" + custPhone + '\'' +
                    ", custCreateTime=" + custCreateTime +
                    '}';
        }
    }

CustomerMapper

  package com.itheima.mapper;
    
    import com.itheima.pojo.Customer;
    
    import java.util.List;
    
    /**
     * @author :yuanjian
     * @date :Created in 2020/10/20 14:45
     * @description:持久化层
     */
    public interface CustomerMapper {
    
        /**
         * @param customer 用户对象信息
         * @return 影响行数
         * @Description 保存用户
         */
        Integer saveCustomer(Customer customer);
    
        /**
         * @Description 删除用户
         * @param custId 用户Id
         * @return 影响行数
         */
        Integer deleteCustomer(Integer custId);
    
        /**
         * @Description 修改用户
         * @param customer 用户对象,其中custId不可以为空
         * @return 影响行数
         */
        Integer updateCusTomerByCustId(Customer customer);
    
        /**
         * @Description 按cusId查询用户
         * @param custId 用户id
         * @return Customer用户对象
         */
        Customer findCustomerByCustId(Integer custId);
    
        /**
         * @Description 按cusId查询用户
         * @param custName 用户名称
         * @return Customer用户对象
         */
        List<Customer> findCustomerByCustName(String custName);
    
        /**
         * @Description 查询所有用户
         * @return 所有用户
         */
        List<Customer> findAll();
    
    }

CustomerMapper.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.itheima.mapper.CustomerMapper">

    <resultMap id="customerResultMap" type="com.itheima.pojo.Customer">
        <id property="custId" jdbcType="INTEGER" column="cust_id"/>
        <result property="custName" jdbcType="VARCHAR" column="cust_name"/>
        <result property="custSource" jdbcType="VARCHAR" column="cust_source"/>
        <result property="custIndustry" jdbcType="VARCHAR" column="cust_industry"/>
        <result property="custLevel" jdbcType="VARCHAR" column="cust_level"/>
        <result property="custAddress" jdbcType="VARCHAR" column="cust_address"/>
        <result property="custPhone" jdbcType="VARCHAR" column="cust_phone"/>
    </resultMap>

    <insert id="saveCustomer" parameterType="com.itheima.pojo.Customer">
      insert into `day08_ssm_customer` (`cust_name`,`cust_source`,`cust_industry`,`cust_level`,`cust_address`,`cust_phone`)
	  values(#{custName},#{custSource},#{custIndustry},#{custLevel},#{custAddress},#{custPhone});
    </insert>

    <delete id="deleteCustomer" parameterType="integer">
		delete from `day08_ssm_customer` where cust_id =#{custId}
	</delete>

    <update id="updateCusTomerByCustId" parameterType="com.itheima.pojo.Customer">
        update `day08_ssm_customer`
        <set>
            <if test="custName!=null">
                cust_name =#{custName},
            </if>
            <if test="custSource!=null">
                cust_source =#{custSource},
            </if>
            <if test="custIndustry!=null">
                cust_industry =#{custIndustry},
            </if>
            <if test="custLevel!=null">
                cust_level =#{custLevel},
            </if>
            <if test="custAddress!=null">
                cust_address =#{custAddress},
            </if>
            <if test="custPhone!=null">
                cust_phone =#{custPhone},
            </if>
        </set>
        where cust_id =#{custId}
    </update>

    <select id="findCustomerByCustId" resultMap="customerResultMap" parameterType="integer">
        select * from `day08_ssm_customer` where cust_id=#{custId}
    </select>

    <select id="findCustomerByCustName" resultMap="customerResultMap" parameterType="java.lang.String">
		select * from `day08_ssm_customer` where cust_name like concat('%',#{custName},'%')
	</select>

    <select id="findAll" resultMap="customerResultMap">
		select * from `day08_ssm_customer`
	</select>

</mapper>

CuseomerService.java

 package com.itheima.service;
    
    import com.itheima.pojo.Customer;
    
    import java.util.List;
    
    /**
     * @Description:客户服务层接口
     */
    public interface CustomerService {
    
        /**
         * @Description 保存用户
         * @param customer 用户对象信息
         * @return 影响行数
         */
        Integer saveCustomer(Customer customer);
    
        /**
         * @Description 删除用户
         * @param custId 用户Id
         * @return 影响行数
         */
        Integer deleteCustomer(Integer custId);
    
        /**
         * @Description 修改用户
         * @param customer 用户对象,其中custId不可以为空
         * @return 影响行数
         */
        Integer updateCusTomerByCustId(Customer customer);
    
        /**
         * @Description 按cusId查询用户
         * @param custId 用户id
         * @return Customer用户对象
         */
        Customer findCustomerByCustId(Integer custId);
    
        /**
         * @Description 按cusId查询用户
         * @param custName 用户名称
         * @return Customer用户对象
         */
        List<Customer> findCustomerByCustName(String custName);
    
        /**
         * @Description 查询所有用户
         * @return 所有用户
         */
        List<Customer> findAll();
    }

CustomerServiceImpl.java

package com.itheima.service.impl;

import com.itheima.mapper.CustomerMapper;
import com.itheima.pojo.Customer;
import com.itheima.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author :yuanjian
 * @date :Created in 2020/10/20 14:49
 * @description:
 */
@Service("customerService")
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    CustomerMapper customerMapper;

    @Override
    @Transactional
    public Integer saveCustomer(Customer customer) {
        return customerMapper.saveCustomer(customer);
    }

    @Override
    @Transactional
    public Integer deleteCustomer(Integer custId) {
        return customerMapper.deleteCustomer(custId);
    }

    @Override
    @Transactional
    public Integer updateCusTomerByCustId(Customer customer) {
        return customerMapper.updateCusTomerByCustId(customer);
    }

    @Override
    public Customer findCustomerByCustId(Integer custId) {
        return customerMapper.findCustomerByCustId(custId);
    }

    @Override
    public List<Customer> findCustomerByCustName(String custName) {
        return customerMapper.findCustomerByCustName(custName);
    }

    @Override
    public List<Customer> findAll() {
        return customerMapper.findAll();
    }
}

LogInfoService.java

    package com.itheima.service;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    
    /**
     * @author :yuanjian
     * @date :Created in 2020/10/20 15:46
     * @description:日志服务
     */
    public interface LogInfoService {
    
        /**
         * @Description 前置通知
         * @MethodName beforeLogInfo
    
         */
        void beforeLogInfo(JoinPoint joinPoint);
    
        /**
         * @Description 后置正常返回通知
         * @MethodName afterReturningLogInfo
         */
        void afterReturningLogInfo(JoinPoint joinPoint);
    
        /**
         * @Description 异常通知
         * @MethodName afterThrowingLogInfo
         */
        void afterThrowingLogInfo(JoinPoint joinPoint);
    
        /**
         * @Description 最终通知
         * @MethodName afterLogInfo
         */
        void afterLogInfo(JoinPoint joinPoint);
    
        /**
         * @Description 环绕通知
         * @MethodName aroundLogInfo
         */
        Object aroundLogInfo(ProceedingJoinPoint joinPoint);
    }

LogInfoServiceImpl.java

    package com.itheima.service.impl;
    
    import com.itheima.service.LogInfoService;
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.*;
    import org.aspectj.lang.reflect.MethodSignature;
    import org.springframework.stereotype.Component;
    
    import java.lang.reflect.Method;
    
    /**
     * @author :yuanjian
     * @date :Created in 2020/10/20 15:47
     * @description:
     */
    @Component
    @Aspect
    public class LogInfoServiceImpl implements LogInfoService {
    
        @Pointcut("execution(* com.itheima.service.impl.*.*(..))")
        public void pt1(){}
    
    
        @Override
        @Before("pt1()")
        public void beforeLogInfo(JoinPoint joinPoint) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            System.out.println("前置通知:"+method.getName());
        }
    
        @Override
        @AfterReturning("pt1()")
        public void afterReturningLogInfo(JoinPoint joinPoint) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            System.out.println("后置正常通知:"+method.getName());
        }
    
        @Override
        @AfterThrowing("pt1()")
        public void afterThrowingLogInfo(JoinPoint joinPoint) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            System.out.println("后置异常通知:"+method.getName());
        }
    
        @Override
        @After("pt1()")
        public void afterLogInfo(JoinPoint joinPoint) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            System.out.println("后置最终通知:"+method.getName());
        }
    
        @Override
        @Around("pt1()")
        public Object aroundLogInfo(ProceedingJoinPoint joinPoint) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Method method = methodSignature.getMethod();
            try {
                System.out.println("环绕-前置通知:"+method.getName());
                Object object = joinPoint.proceed();
                System.out.println("环绕-后置正常通知:"+method.getName());
                return object;
            } catch (Throwable throwable) {
                System.out.println("环绕-后置异常通知:"+method.getName());
                throw new RuntimeException(throwable);
            }finally {
                System.out.println("环绕-最终通知:"+method.getName());
            }
        }
    }

CustomerController.java

  package com.itheima.controller;
    
    import com.itheima.pojo.Customer;
    import com.itheima.service.CustomerService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.List;
    
    /**
     * @author :yuanjian
     * @date :Created in 2020/10/20 15:56
     * @description:
     */
    @Controller
    @RequestMapping("/customer")
    public class CustomerController {
    
        @Autowired
        private CustomerService customerService;
    
        @RequestMapping("list")
        public String list(Model model){
            List<Customer> customerList = customerService.findAll();
            model.addAttribute("list",customerList);
            return "list";
        }
    
        @RequestMapping("tofind")
        public String tofind(String custName,Model model){
            List<Customer> customerList = customerService.findCustomerByCustName(custName);
            model.addAttribute("list",customerList);
            return "list";
        }
    
        @RequestMapping("toAdd")
        public String toAdd(){
            return "add";
        }
    
        @RequestMapping("doAdd")
        public String doAdd(Customer customer){
            customerService.saveCustomer(customer);
            return "redirect:/customer/list";
        }
    
        @RequestMapping("toUpdate")
        public String toUpdate(Integer custId,Model model){
            Customer customer = customerService.findCustomerByCustId(custId);
    //        System.out.println("customer = " + customer);
            model.addAttribute("customer",customer);
            return "update";
        }
    
        @RequestMapping("doUpdate")
        public String doUpdate(Customer customer){
            customerService.updateCusTomerByCustId(customer);
            return "redirect:/customer/list";
        }
    
        @RequestMapping("doDel")
        public String doDel(Integer custId){
            customerService.deleteCustomer(custId);
            return "redirect:/customer/list";
        }
    }

db.properties

  dataSource.driverClassName=com.mysql.jdbc.Driver
  dataSource.url=jdbc:mysql://127.0.0.1:3306/heimassm
  dataSource.username=root
  dataSource.password=123456

log4j2.xml

 <?xml version="1.0" encoding="UTF-8"?>
    <!-- 设置log4j2的自身log级别为warn -->
    <!-- OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
    <Configuration status="DEBUG">
        <Appenders>
            <!-- 控制台输出 -->
            <Console name="Console" target="SYSTEM_OUT">
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>
                <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
            </Console>
    
            <RollingFile name="RollingFileDebug" fileName="F:/Heima/code/05SSM/day08_ssm_project/logs/debug.log"
                         filePattern="F:/Heima/code/05SSM/day08_ssm_project/logs/$${date:yyyy-MM}/debug-%d{yyyy-MM-dd}-%i.log">
                <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
                <Filters>
                    <ThresholdFilter level="DEBUG"/>
                    <ThresholdFilter level="INFO" onMatch="DENY" onMismatch="NEUTRAL"/>
                </Filters>
                <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
                <Policies>
                    <TimeBasedTriggeringPolicy/>
                    <SizeBasedTriggeringPolicy size="100 MB"/>
                </Policies>
                <!--最多保留20个日志文件-->
                <DefaultRolloverStrategy max="20" min="0" />
            </RollingFile>
    
            <RollingFile name="RollingFileInfo" fileName="F:/Heima/code/05SSM/day08_ssm_project/logs/info.log"
                         filePattern="F:/Heima/code/05SSM/day08_ssm_project/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
                <Filters>
                    <ThresholdFilter level="INFO"/>
                    <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/>
                </Filters>
                <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
                <Policies>
                    <TimeBasedTriggeringPolicy/>
                    <SizeBasedTriggeringPolicy size="100 MB"/>
                </Policies>
                <!--最多保留20个日志文件-->
                <DefaultRolloverStrategy max="20" min="0" />
            </RollingFile>
    
            <RollingFile name="RollingFileWarn" fileName="F:/Heima/code/05SSM/day08_ssm_project/logs/warn.log"
                         filePattern="F:/Heima/code/05SSM/day08_ssm_project/logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
                <Filters>
                    <ThresholdFilter level="WARN"/>
                    <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
                </Filters>
                <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
                <Policies>
                    <TimeBasedTriggeringPolicy/>
                    <SizeBasedTriggeringPolicy size="100 MB"/>
                </Policies>
                <!--最多保留20个日志文件-->
                <DefaultRolloverStrategy max="20" min="0" />
            </RollingFile>
    
            <RollingFile name="RollingFileError" fileName="F:/Heima/code/05SSM/day08_ssm_project/logs/error.log"
                         filePattern="F:/Heima/code/05SSM/day08_ssm_project/logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
                <ThresholdFilter level="ERROR"/>
                <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
                <Policies>
                    <TimeBasedTriggeringPolicy/>
                    <SizeBasedTriggeringPolicy size="100 MB"/>
                </Policies>
                <!--最多保留20个日志文件-->
                <DefaultRolloverStrategy max="20" min="0" />
            </RollingFile>
    
            <RollingFile name="RollingFileFatal" fileName="F:/Heima/code/05SSM/day08_ssm_project/logs/fatal.log"
                         filePattern="F:/Heima/code/05SSM/day08_ssm_project/logs/$${date:yyyy-MM}/fatal-%d{yyyy-MM-dd}-%i.log">
                <ThresholdFilter level="FATAL"/>
                <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
                <Policies>
                    <TimeBasedTriggeringPolicy/>
                    <SizeBasedTriggeringPolicy size="100 MB"/>
                </Policies>
                <!--最多保留20个日志文件-->
                <DefaultRolloverStrategy max="20" min="0" />
            </RollingFile>
        </Appenders>
        <Loggers>
            <!-- 将业务dao接口填写进去,并用控制台输出即可 -->
            <logger name="com.itheima.mapper" level="DEBUG" additivity="false">
                <appender-ref ref="Console"/>
            </logger>
    
            <logger name="com.itheima.service" level="DEBUG" additivity="false">
                <appender-ref ref="Console"/>
            </logger>
    
            <Root level="all">
                <appender-ref ref="Console"/>
                <appender-ref ref="RollingFileDebug"/>
                <appender-ref ref="RollingFileInfo"/>
                <appender-ref ref="RollingFileWarn"/>
                <appender-ref ref="RollingFileError"/>
                <appender-ref ref="RollingFileFatal"/>
            </Root>
        </Loggers>
    </Configuration>

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.itheima</groupId>
        <artifactId>day08_ssm_project</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>war</packaging>
    
        <properties>
            <!--spring 版本-->
            <spring.version>5.0.10.RELEASE</spring.version>
            <!-- log4j日志版本 -->
            <log4j.version>2.8.2</log4j.version>
            <!--jackson版本-->
            <jackson.version>2.9.0</jackson.version>
            <!-- jstl标签版本 -->
            <jstl.version>1.2</jstl.version>
            <!--servlet版本-->
            <servlet.version>3.0.1</servlet.version>
        </properties>
    
    
        <dependencies>
            <!--jstl-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>${jstl.version}</version>
            </dependency>
            <!--servlet-->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>${servlet.version}</version>
                <scope>provided</scope>
            </dependency>
            <!--spring 容器依赖-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--spring jdbc依赖-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--spring aop依赖-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--spring 事务依赖-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--spring mvc容器依赖-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--spring 测试依赖-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!--mybatis-spring依赖-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>1.3.1</version>
            </dependency>
    
            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.5</version>
            </dependency>
            <!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.30</version>
            </dependency>
            <!--druid-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.0.29</version>
            </dependency>
            <!-- log4j2驱动依赖 -->
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-api</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-web</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <!--jackson-->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-core</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-annotations</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <configuration>
                        <uriEncoding>utf-8</uriEncoding>
                        <port>8080</port>
                        <path>/</path>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.1</version>
                    <configuration>
                        <target>8</target>
                        <source>8</source>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>

list.jsp

 <%@ page import="java.util.List" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="C" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    <!DOCTYPE html>
    <!-- 网页使用的语言 -->
    <html lang="zh-CN">
    <head>
        <!-- 指定字符集 -->
        <meta charset="utf-8">
        <!-- 使用Edge最新的浏览器的渲染方式 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
        width: 默认宽度与设备的宽度相同
        initial-scale: 初始的缩放比,为1:1 -->
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
        <title>用户信息管理系统</title>
    
        <!-- 1. 导入CSS的全局样式 -->
        <link href="../../static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
        <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
        <script src="../../static/js/jquery-1.12.4.min.js"></script>
        <!-- 3. 导入bootstrap的js文件 -->
        <script src="../../static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
        <style type="text/css">
            td, th {
                text-align: center;
            }
        </style>
    </head>
    <body>
    
    <div class="container">
    
        <div class="row">
            <div class="col-md-2 col-md-offset-5"><h3>客户信息列表</h3></div>
            <div class="col-md-2 col-md-offset-3"><h3><button type="button" class="btn btn-primary" onclick="toAdd()">添加客户</button></h3></div>
        </div>
    
            <div class="input-group col-md-3">
                <input type="text" class="form-control" id="custName" placeholder="输入姓名模糊查询">
                <span class="input-group-addon"><span class="glyphicon glyphicon-search" onclick="tofind()"></span></span>
            </div>
    
        <table border="1" class="table table-bordered table-hover">
            <tr class="success">
                <td>#</td>
                <th>编号</th>
                <th>公司名称</th>
                <th>信息来源</th>
                <th>所属行业</th>
                <th>级别</th>
                <th>联系地址</th>
                <th>联系电话</th>
                <th>操作</th>
            </tr>
            <c:forEach items="${list}" var="customer" varStatus="status">
            <tr>
                <td>${status.index+1}</td>
                <td>${customer.custId}</td>
                <td>${customer.custName}</td>
                <td>${customer.custSource}</td>
                <td>${customer.custIndustry}</td>
                <td>${customer.custLevel}</td>
                <td>${customer.custAddress}</td>
                <td>${customer.custPhone}</td>
                <td>
                    <button type="button" class="btn btn-info" onclick="toUpdate(${customer.custId})">修改</button>
                    <button type="button" class="btn btn-danger" onclick="doDel('${customer.custId}')">删除</button>
                </td>
            </tr>
            </c:forEach>
        </table>
    
    </div>
    <script>
        //模糊查询
        function tofind() {
            let custName = document.getElementById('custName').value;
            window.location.href="${pageContext.request.contextPath}/customer/tofind?custName="+custName;
        }
        // 添加用户
        function toAdd(id) {
            window.location.href="${pageContext.request.contextPath}/customer/toAdd";
        }
    
        // 修改用户
        function toUpdate(id) {
            window.location.href="${pageContext.request.contextPath}/customer/toUpdate?custId="+id;
        }
        // 删除用户
        function  doDel(id) {
            if(confirm("确定要删除吗?")){
                window.location.href="${pageContext.request.contextPath}/customer/doDel?custId="+id;
            }
        }
    </script>
    </body>
    </html>

add.jsp

 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    <!-- HTML5文档-->
    <!DOCTYPE html>
    <!-- 网页使用的语言 -->
    <html lang="zh-CN">
    <head>
        <!-- 指定字符集 -->
        <meta charset="utf-8">
        <!-- 使用Edge最新的浏览器的渲染方式 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
        width: 默认宽度与设备的宽度相同
        initial-scale: 初始的缩放比,为1:1 -->
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
        <title>添加用户</title>
    
        <!-- 1. 导入CSS的全局样式 -->
        <link href="../../static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
        <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
        <script src="../../static/js/jquery-1.12.4.min.js"></script>
        <!-- 3. 导入bootstrap的js文件 -->
        <script src="../../static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container text-left">
        <center><h3>添加联系人页面</h3></center>
        <form id="userForm" action="${pageContext.request.contextPath}/customer/doAdd" method="post" class="form-horizontal">
            <div class="form-group">
                <label class="col-lg-2 control-label" for="custName">公司名称:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custName" name="custName" placeholder="请输入公司名称">
                </div>
            </div>
    
            <div class="form-group">
                <label class="col-lg-2 control-label" for="custSource">信息来源:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custSource" name="custSource" placeholder="请输入信息来源">
                </div>
            </div>
    
            <div class="form-group">
                <label for="custIndustry" class="control-label col-lg-2">所属行业:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custIndustry" name="custIndustry" placeholder="请输入所属行业">
                </div>
            </div>
    
            <div class="form-group">
                <label for="custLevel" class="control-label col-lg-2">级别:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custLevel" name="custLevel" placeholder="请输入级别">
                </div>
            </div>
    
            <div class="form-group">
                <label for="custAddress" class="control-label col-lg-2">联系地址:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custAddress" name="custAddress" placeholder="请输入联系地址">
                </div>
            </div>
    
            <div class="form-group">
                <label for="custPhone" class="control-label col-lg-2">联系电话:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custPhone"  name="custPhone" placeholder="请输入联系电话"/>
                </div>
            </div>
    
            <div class="form-group" style="text-align: center">
                <input class="btn btn-primary" type="submit" value="提交" />
                <input class="btn btn-default" type="reset" value="重置" />
                <input class="btn btn-default" type="button" value="返回" onclick="returnList()"/>
            </div>
        </form>
    </div>
    <script>
        function returnList(){
            window.history.go(-1);
        }
    </script>
    </body>
    </html>

update.jsp

  <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    
    <!-- HTML5文档-->
    <!DOCTYPE html>
    <!-- 网页使用的语言 -->
    <html lang="zh-CN">
    <head>
        <!-- 指定字符集 -->
        <meta charset="utf-8">
        <!-- 使用Edge最新的浏览器的渲染方式 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
        width: 默认宽度与设备的宽度相同
        initial-scale: 初始的缩放比,为1:1 -->
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
        <title>添加用户</title>
    
        <!-- 1. 导入CSS的全局样式 -->
        <link href="../../static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
        <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
        <script src="../../static/js/jquery-1.12.4.min.js"></script>
        <!-- 3. 导入bootstrap的js文件 -->
        <script src="../../static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container text-left">
        <center><h3>修改联系人页面</h3></center>
        <form id="userForm" action="${pageContext.request.contextPath}/customer/doUpdate" method="post" class="form-horizontal">
            <input type="hidden" name="custId" value="${customer.custId}"/>
            <div class="form-group">
                <label class="col-lg-2 control-label" for="custName">公司名称:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custName" value="${customer.custName}" name="custName" placeholder="请输入公司名称">
                </div>
            </div>
    
            <div class="form-group">
                <label class="col-lg-2 control-label" for="custSource">信息来源:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custSource" value="${customer.custSource}" name="custSource" placeholder="请输入信息来源">
                </div>
            </div>
    
            <div class="form-group">
                <label for="custIndustry" class="control-label col-lg-2">所属行业:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custIndustry" value="${customer.custIndustry}" name="custIndustry" placeholder="请输入所属行业">
                </div>
            </div>
    
            <div class="form-group">
                <label for="custLevel" class="control-label col-lg-2">级别:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custLevel" value="${customer.custLevel}" name="custLevel" placeholder="请输入级别">
                </div>
            </div>
    
            <div class="form-group">
                <label for="custAddress" class="control-label col-lg-2">联系地址:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custAddress" value="${customer.custAddress}" name="custAddress" placeholder="请输入联系地址">
                </div>
            </div>
    
            <div class="form-group">
                <label for="custPhone" class="control-label col-lg-2">联系电话:</label>
                <div class="col-lg-8">
                    <input type="text" class="form-control" id="custPhone" value="${customer.custPhone}" name="custPhone" placeholder="请输入联系电话"/>
                </div>
            </div>
    
            <div class="form-group" style="text-align: center">
                <input class="btn btn-primary" type="submit" value="提交" />
                <input class="btn btn-default" type="reset" value="重置" />
                <input class="btn btn-default" type="button" value="返回" onclick="returnList()"/>
            </div>
        </form>
    </div>
    <script>
        function returnList(){
            window.history.go(-1);
        }
    </script>
    </body>
    </html>

3.使用xml-注解配置

1.spring.xml

在spring.xml中需要配置:

1.注解扫描(扫描,配置自动扫描service层,且只启用@Service):

代替service的bean创建
在这里插入图片描述

2.开启事务自动配置(使用注解方式开启事务)

直接在切入的方法中配置事务,
在这里插入图片描述
代替如下配置。
在这里插入图片描述

3.开启AOP自动配置(使用注解方式开启aop)

在logInfoServiceImpl中直接使用注解配置aop的日志通知,
在这里插入图片描述
代替了如下的xml配置。
在这里插入图片描述

spring.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">
    
        <!-- 1、扫描,配置自动扫描service层,且只启用@Service-->
        <context:component-scan base-package="com.itheima">
            <context:exclude-filter type="annotation"                                           	                                       expression="org.springframework.stereotype.Controller"/>
            <context:exclude-filter type="annotation"                                                                                   expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
        </context:component-scan>
    
        <!--2、开启事务自动配置-->
        <tx:annotation-driven/>
    
        <!--3、开启AOP自动配置-->
        <aop:aspectj-autoproxy/>
    
    </beans>

2.spring-mybatis.xml

在spring-mybatis.xml中需要配置:

1.加载外部配置db.properties

2.配置数据源(druidDataSource)

3.配置事务管理器(transactionManager)

4.配置和MyBatis的整合

把原来配置在sqlMapConfig中的配置全部交由spring来配置

sqlMapConfig.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>
    
        <!--加载外部的properties文件-->
        <properties resource="jdbc.properties"></properties>
    
        <settings>
            <!--开启全局加载-->
            <setting name="lazyLoadingEnabled" value="true"/>
            <setting name="logImpl" value="LOG4J" />
        </settings>
    
        <!--给类或包下面的类起别名,目标:在接口映射文件中只需要写类名就可以-->
        <typeAliases>
            <package name="com.itheima.case2.pojo"/>
        </typeAliases>
    
        <environments default="mysql">
            <environment id="mysql">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="pooled">
                    <property name="driver" value="${driver}"/>
                    <property name="url" value="${url}"/>
                    <property name="username" value="${username}"/>
                    <property name="password" value="${password}"/>
                </dataSource>
            </environment>
    
    
        </environments>
    
        <!--加载接口映射文件-->
        <mappers>
            <!--加载指定包下所有的接口映射文件-->
            <package name="com.itheima.case2.dao"/>
        </mappers>
    </configuration>
    

5.配置扫描器,创建所有mapper对象,将mybatis接口的实现加入到ioc容器中

相当于将dao层的所有mapper对象注入到spring容器中,相当于如下:

spring-mybatis.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 http://www.springframework.org/schema/context/spring-context.xsd ">
    
    
        <!-- Spring-mybatis的配置文件,这里主要配置和业务逻辑有关的 -->
        <!--=================== 数据源,事务控制,xxx ================-->
        <context:property-placeholder location="classpath:db.properties"/>
    
        <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${dataSource.driverClassName}"/>
            <property name="url" value="${dataSource.url}"/>
            <property name="username" value="${dataSource.username}"/>
            <property name="password" value="${dataSource.password}"/>
        </bean>
    
        <!-- ===============事务控制的配置 ================-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="druidDataSource"></property>
        </bean>
    
        <!--================== 配置和MyBatis的整合=============== -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 传入 数据源 -->
            <property name="dataSource" ref="druidDataSource"/>
            <!-- 传入 pojo类所在包 -->
            <property name="typeAliasesPackage" value="com.itheima.pojo"/>
            <!-- 传入 mapper.xml映射文件所在路径 -->
            <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
            <!-- 加载mybatis的全局配置文件:settings标签-->
            <!--   <property name="configuration">标签和
               <property name="configLocation" value="classpath:mybatis-config.xml"></property>标签
               同时配置会起冲突,所以只能配置其中一个
            -->
            <property name="configuration">
                <bean class="org.apache.ibatis.session.Configuration">
                    <!--引入日志-->
                    <property name="logImpl" value="org.apache.ibatis.logging.log4j2.Log4j2Impl"></property>
                    <!--mybatis驼峰映射-->
                    <property name="mapUnderscoreToCamelCase" value="true"/>
                </bean>
            </property>
        </bean>
    
        <!-- 配置扫描器,创建所有mapper对象,将mybatis接口的实现加入到ioc容器中 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 传入 sqlSessionFactory -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!-- 传入 mapper接口所在包 -->
            <property name="basePackage" value="com.itheima.mapper"/>
        </bean>
    
    </beans>

3.spring-mvc.xml

在spring-mvc.xml中需要配置:

1.只开启controller层的扫描

2.显式配置处理映射器和处理适配器等

3.配置视图扫描器

4.释放静态资源

spring-mvc.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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!--只开启controller层的扫描-->
        <context:component-scan base-package="com.itheima.controller"/>
        <!--显式配置处理映射器和处理适配器等-->
        <mvc:annotation-driven/>
        <!--配置视图扫描器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
        <!--释放静态资源-->
        <mvc:default-servlet-handler/>
    
    </beans>
    

4.web.xml

在web.xml中需要配置:

1.配置加载spring,spring-mybatis配置文件

2.配置监听器:ContextLoaderListener

3.配置前端控制器:DispatcherServlet

4.配置字符集编码过滤器:CharacterEncodingFilter

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:spring-mybatis.xml
                classpath:spring.xml
            </param-value>
        </context-param>
    
        <!--配置监听器:ContextLoaderListener,说明:
            1.配置ContextLoaderListener监听器,用于监听ServletContext对象创建,一旦ServletContext对象创建,
                就创建spring的ioc容器。并且ioc容器放入ServletContext上下文中
            2.该监听器默认只能加载WEB-INF目录下,名称叫做applicationContext.xml配置文件
            3.通过<context-param>全局参数标签,指定加载spring配置文件的位置
        -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    
        <!--配置前端控制器:DispatcherServlet-->
        <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:spring-mvc.xml</param-value>
            </init-param>
            <!--配置什么时候加载前端控制器,说明:
              1.配置大于等于0的整数,表示在tomcat启动的时候,就加载前端控制器
              2.配置小于0的整数,表示在第一次请求到达的时候加载前端控制器
            -->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcherServlet</servlet-name>
            <!--配置请求的路径规则,说明:
                 1.*.do,表示以.do结尾的请求进入前端控制器
                 2./,表示所有请求都进入前端控制器
            -->
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!--配置字符集编码过滤器:CharacterEncodingFilter-->
        <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>
    </web-app>

4.day09_maven_ssm_annotation项目(使用纯注解)

纯注解方式将xml-注解配置方式的spring.xml,spring-mybatis.xml,spring-mvc.xml和web.xml换成了如下的配置类,其余不变。\

且需要在pom.xml中加上下面这段代码,引入插件,声明打包时,不需要web.xml 。

     <!-- 声明打包时,不需要web.xml -->
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <version>2.4</version>
    </plugin>

在这里插入图片描述

5.使用纯注解配置

1.SpringConfig.java

在SpringConfig.java中需要配置:

1.使用@Configuration声明配置类

2.使用@EnableAspectJAutoProxy开启自动注解aop

3.使用@EnableTransactionManagement开启自动注解事务

4.使用@ComponentScan 声明除Controller注解之外的所有自动装配

SpringConfig.java中的代码

 package com.itheima.config;
    
    import org.springframework.context.annotation.*;
    import org.springframework.stereotype.Controller;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    
    /**
     * @Description:spring基础配置
     * @Configuration 声明配置类
     * @EnableAspectJAutoProxy 自动开启AOP
     * @ComponentScan 声明除Controller注解之外的所有自动装配
     */
    @Configuration
    @EnableAspectJAutoProxy
    @EnableTransactionManagement
    @ComponentScan(value = {"com.itheima"},
            excludeFilters = {
                    @ComponentScan.Filter(
                            type = FilterType.ANNOTATION,
                            classes = {Controller.class, ControllerAdvice.class})})
    @Import({MybatisConfig.class,SpringMvcConfig.class})
    public class SpringConfig {
    }

2.MybatisConfig.java

在MybatisConfig.java中需要配置:

1.使用@Configuration:声明为配置文件

2.使用@PropertySource 导入外部的db.properties文件

3.@Bean(“druidDataSource”)配置druid数据源

4.@Bean(“transactionManager”)配置事务管理器transactionManager

5.@Bean(“sqlSessionFactory”)配置和MyBatis的整合

6.使用@MapperScan 这里管理的是mapper类,注入sqlSessionFactory

MybatisConfig.java中的代码

 package com.itheima.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import org.apache.ibatis.logging.log4j2.Log4j2Impl;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    
    import java.io.IOException;
    
    /**
     * @Description:mybatis配置类
     * @Configuration:声明为配置文件
     * @PropertySource 导入外部的db.properties文件
     * @MapperScan 这里管理的是mapper类,注入sqlSessionFactory
     */
    @Configuration
    @PropertySource(value = "classpath:db.properties")
    @MapperScan(basePackages = {"com.itheima.mapper"},sqlSessionFactoryRef = "sqlSessionFactory")
    public class MybatisConfig {
    
        @Value("${dataSource.driverClassName}")
        private String driverClassName;
    
        @Value("${dataSource.url}")
        private String url;
    
        @Value("${dataSource.username}")
        private String username;
    
        @Value("${dataSource.password}")
        private String password;
    
        /**
         * @Description 数据源配置
         */
        @Bean("druidDataSource")
        public DruidDataSource druidDataSource(){
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        }
    
        /**
         * @Description 事务管理器配置,注意默认名称:transactionManager
         */
        @Bean("transactionManager")
        public DataSourceTransactionManager transactionManager(){
            DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
            //配置数据源
            dataSourceTransactionManager.setDataSource(druidDataSource());
            return  dataSourceTransactionManager;
        }
    
        /**
         * @Description 管理mybatis的SqlSessionFactoryBean
         */
        @Bean("sqlSessionFactory")
        public SqlSessionFactoryBean sqlSessionFactory() {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            //配置数据源
            sqlSessionFactoryBean.setDataSource(druidDataSource());
            //配置实体类管理
            sqlSessionFactoryBean.setTypeAliasesPackage("com.itheima.pojo");
            try {
                //配置mapper的XML,PathMatchingResourcePatternResolver是一个Ant模式通配符的Resource查找器,可以用来查找类路径下或者文件系统中的资源。
                sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("mapper/*Mapper.xml"));
            } catch (IOException e) {
    
            }
            //配置日志选型
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            configuration.setLogImpl(Log4j2Impl.class);
            sqlSessionFactoryBean.setConfiguration(configuration);
            return sqlSessionFactoryBean;
        }
    }

3.SpringMvcConfig.java

在SpringMvcConfig.java中需要配置:

1.使用@EnableWebMvc 自动开启springMVC相当于<mvc:annotation-driven >

2.@ComponentScan(value = {“com.itheima.controller”}) 自动扫描web层装配bean

3.InternalResourceViewResolver viewResolver(){)配置资源解析路径和后缀名

4.void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)释放静态资源

SpringMvcConfig.java中的代码

package com.itheima.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @Description:springMVC配置,spring5之后不建议使用WebMvcConfigurerAdapter
 * @EnableWebMvc 自动开启springMVC
 * @ComponentScan 自动扫描web层装配bean
 *
 */
@EnableWebMvc
@ComponentScan(value = {"com.itheima.controller"})
public class SpringMvcConfig extends WebMvcConfigurationSupport {

    /**
     * @Description 配置资源解析路径和后缀名
     */
    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return  viewResolver;
    }


   /*@Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/static/**").addResourceLocations("/static/");
   }*/


    //释放静态资源

    @Override
    protected void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
        //super.configureDefaultServletHandling(configurer);
    }
}

4.ProjectInitConfig.java

在ProjectInitConfig.java中需要配置:

1.void onStartup(ServletContext servletContext)配置过滤器

2.Class<?>[] getRootConfigClasses() 加载spring的配置

3.Class<?>[] getServletConfigClasses()加载SpringMVC的配置

4.配置dispatcherServlet的映射路径

ProjectInitConfig.java中的代码

package com.itheima.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.FilterRegistration;
import javax.servlet.Registration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

/**
 * @Description:替换web.xml
 */
@Configuration
public class ProjectInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        //注册过滤器
        FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("CharacterEncodingFilter", CharacterEncodingFilter.class);
        //设置过滤器的初始化参数
        characterEncodingFilter.setInitParameter("encoding","utf-8");
        //配置过滤器的映射路径
        characterEncodingFilter.addMappingForUrlPatterns(null,true,"/*");

        super.onStartup(servletContext);
    }

    /**
     * spring的配置
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    /**
     * springmvc配置类
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    /**
     * 配置dispatcherServlet的映射路径
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"*.do"};
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值