【SSM】xml配置版整合

1、基础配置

1、新建Maven项目,并添加web支持
2、导入依赖
    <!--导入依赖-->
    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <!--事务织入包-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

    </dependencies>
3、Maven静态资源过滤
<!--静态资源过滤-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
4、在Project Structure中进行操作

在这里插入图片描述

5、建立ssm项目基本结构与配置框架

在这里插入图片描述

2、MyBatis层

1、mybatis-config.xml

有关数据源的配置被Spring接管
在mybatis-config中只需要做如下必要配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
    <!--配置日志信息-->
        <setting name="logImpl" value="LOG4J"/>
    </settings>
    <typeAliases>
        <package name="indi.zhihuali.pojo"/>
    </typeAliases>
    <mappers>
        <mapper class="indi.zhihuali.mapper.BooksMapper"/>
    </mappers>
</configuration>
2、db.properties

Mysql 8.0+ 驱动包需要添加对时区的配置,如果是5.x可以删除时区配置,同时修改jdbc.driver=com.mysql.jdbc.Driver

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=1234
3、在IDEA中关联数据库
4、编写实体类

使用Lombok简化实体类开发

package indi.zhihuali.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.Alias;
/**
 * @ program: spring-mvc
 * @ description:
 * @ author: zhihua li
 * @ create: 2021-04-22 14:23
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Alias("books")	//结合mybatis-config中的typeAlias配置别名
public class Books {
    private Integer bookID;
    private String bookName;
    private Integer bookCounts;
    private String detail;
}
5、编写Mapper

注意:当使用select语句查询count(*)等返回Integer类型的数据时,需要添加resultType属性

package indi.zhihuali.mapper;

import indi.zhihuali.pojo.Books;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.awt.print.Book;
import java.util.List;

/**
 * @ program: spring-mvc
 * @ description:
 * @ author: zhihua li
 * @ create: 2021-04-22 14:31
 **/

public interface BooksMapper {
    public int addBook(Books books);

    public int deleteBookById(@Param("bookID") int id);

    public int updateBook(Books books);

    public Books queryBookById(@Param("bookID") int id);

    public List<Books> queryAllBook();

    public List<Books> queryBookByBookName(@Param("bookName") String name);
}

6、编写对应的Mapper.xml

BooksMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="indi.zhihuali.mapper.BooksMapper">

    <insert id="addBook" parameterType="books">
        insert into books(bookName, bookCounts, detail)
        values (#{bookName}, #{bookCounts}, #{detail})
    </insert>

    <delete id="deleteBookById" parameterType="int">
        delete
        from books
        where bookID = #{bookID};
    </delete>

    <update id="updateBook" parameterType="books">
        update books
        set bookName   = #{bookName},
            bookCounts = #{bookCounts},
            detail     = #{detail}
        where bookID = #{bookID}
    </update>

    <select id="queryBookById" resultType="books">
        select *
        from books
        where bookID = #{bookID}
    </select>

    <select id="queryAllBook" resultType="books">
        select *
        from books;
    </select>

    <select id="queryBookByBookName" resultType="books">
    <!--对图书的bookName字段进行模糊查询-->
        select *
        from books
        where bookName like #{bookName}
    </select>

</mapper>
7、编写Service及其实现类

Service调用Mapper层

package indi.zhihuali.service;

import indi.zhihuali.pojo.Books;

import java.util.List;

public interface BooksService {
    public int addBook(Books books);

    public int deleteBookById(int id);

    public int updateBook(Books books);

    public Books queryBookById(int id);

    public List<Books> queryAllBook();

    public List<Books> queryBookByBookName(String name);
}
package indi.zhihuali.service;

import indi.zhihuali.mapper.BooksMapper;
import indi.zhihuali.pojo.Books;

import java.util.List;

public class BooksServiceImpl implements BooksService {
    private BooksMapper booksMapper;

    public void setBooksMapper(BooksMapper booksMapper) {
        this.booksMapper = booksMapper;
    }

    public int addBook(Books books) {
        return booksMapper.addBook(books);
    }

    public int deleteBookById(int id) {
        return booksMapper.deleteBookById(id);
    }

    public int updateBook(Books books) {
        return booksMapper.updateBook(books);
    }

    public Books queryBookById(int id) {
        return booksMapper.queryBookById(id);
    }

    public List<Books> queryAllBook() {
        return booksMapper.queryAllBook();
    }

    public List<Books> queryBookByBookName(String name) {
        return booksMapper.queryBookByBookName(name);
    }
}

采用xml配置的方式,就需要在Spring的配置文件中对业务中需要用到的bean进行手动配置

3、Spring层

1、Spring对Mapper的接管

spring-mapper.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
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--    1.关联数据库配置文件        -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--    2. 使用连接池   -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!--    3.配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--        绑定mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 当mapper接口与配置文件不在同一个包路径下时,可以通过下面的属性进行配置-->
        <property name="mapperLocations" value="classpath:indi/zhihuali/mapper/*.xml"/>
    </bean>

    <!--    配置mapper接口扫描包 动态实现了Dao接口可以注入到Spring容器中  -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--        扫描dao       -->
        <property name="basePackage" value="indi.zhihuali.mapper"/>
    </bean>
    
    <!--简化MapperScannerConfigurer配置,可替换上面的配置-->
    <mybatis-spring:scan base-package="indi.zhihuali.mapper"/>
</beans>

注:上面的MapperScannerConfigurer相关bean配置,可以被下面的语句替换,简化配置信息
<mybatis-spring:scan base-package="indi.zhihuali.mapper"/>

2、Spring对Service的接管

spring-service.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--    1、扫描service下的包-->
    <context:component-scan base-package="indi.zhihuali.service"/>
    <!--    2、将所有的业务类注入spring 可以通过配置或者注解实现  -->
    <bean id="booksService" class="indi.zhihuali.service.BooksServiceImpl">
    	<!-- 		不能直接注入接口,因此要注入实现类 	-->
        <!--        也可以通过@Autowired注解注入,但必须保证在其他相关xml文件中已经配置 此处的booksMapper就已经在spring-mapper.xml中配置好了-->
        <!--        <property name="basePackage" value="indi.zhihuali.mapper"/>             -->
        <property name="booksMapper" ref="booksMapper"></property>
    </bean>
    <!--    3.声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--结合aop实现事务织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* indi.zhihuali.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

4、SpringMVC层

1、配置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">
    <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:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--配置乱码过滤-->
    <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>

    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>
2、SpringMVC对Controller的接管
有关静态资源过滤问题:

如果通过下面的配置:<mvc:default-servlet-handler/>,在jsp页面中仍然无法引入静态资源或无法访问图片等时,需要在配置文件中进行如下配置:

<!--    2、静态资源过滤     -->
    <mvc:default-servlet-handler/>
    <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
    <mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
    <mvc:resources location="/WEB-INF/images/" mapping="/images/**"/>
    <mvc:resources mapping="/fonts/**" location="/WEB-INF/fonts/"/>

springmvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--注解驱动-->
    <mvc:annotation-driven/>
    <!--静态资源过滤-->
    <mvc:default-servlet-handler/>
    <!--扫描包-->
    <context:component-scan base-package="indi.zhihuali.controller"/>
    <!--视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

5、将Spring相关配置文件引入同一xml文件

application.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mapper.xml"/>
    <import resource="classpath:springmvc-config.xml"/>

</beans>

6、整合测试

1、编写Controller
package indi.zhihuali.controller;

import indi.zhihuali.pojo.Books;
import indi.zhihuali.service.BooksService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.awt.print.Book;
import java.util.ArrayList;
import java.util.List;

/**
 * @ program: spring-mvc
 * @ description:
 * @ author: zhihua li
 * @ create: 2021-04-22 14:41
 **/

@Controller
@RequestMapping
public class BookController {

    @Autowired
    private BooksService booksService;

    @RequestMapping("/list")
    public String list(Model model) {
        List<Books> books = booksService.queryAllBook();
        model.addAttribute("books", books);
        return "allBook";
    }

}
2、创建对应的跳转视图

由于SpringMVC中配置了视图解析器,因此在普通请求跳转时,需要将跳转视图创建在web/WEB-INF/jsp/
web/WEB-INF/jsp/allBook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: www
  Date: 2021/4/22
  Time: 15:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>

    </style>
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>书籍列表 ———— 显示所有书籍</small>
                </h1>
            </div>
        </div>
    </div>
</div>

<div class="row clearfix">
    <div class="col-md-12 column">
        <table class="table table-hover table-striped">
            <tr>
                <th>书籍编号</th>
                <th>书籍名称</th>
                <th>书籍数量</th>
                <th>书籍详情</th>
                <th>操作</th>
            </tr>
            <tr>
                <c:forEach var="book" items="${books}">
            <tr>
                <td>${book.bookID}</td>
                <td>${book.bookName}</td>
                <td>${book.bookCounts}</td>
                <td>${book.detail}</td>
            </tr>
            </c:forEach>
            </tr>
        </table>
    </div>
</div>
</body>
</html>
3、使用超链接的方法发起请求
<%--
  Created by IntelliJ IDEA.
  User: www
  Date: 2021/4/22
  Time: 11:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
        a {
            text-decoration: none;
            color: black;
            font-size: 18px;
        }

        h3 {
            width: 100px;
            height: 38px;
            margin: 100px auto;
            text-align: center;
            line-height: 38px;
            background-color: #bfa;
            border-radius: 50%;
        }
    </style>
    <%
        System.out.println("Hello");
    %>
</head>
<body>

<div>
    <a style="color: blue" href="${pageContext.request.contextPath}/list">进入书籍页面</a>
</div>
</body>
</html>

7、报错信息

一些相关的报错信息【文末】

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pascalzhli

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值