Java教程

SSM整合

本文主要是介绍SSM整合,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

数据库环境

创建一个存放书籍数据的数据库表

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books` (
  `id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
  `name` VARCHAR(100) NOT NULL COMMENT '书名',
  `count` INT(11) NOT NULL COMMENT '数量',
  `detail` VARCHAR(200) NOT NULL COMMENT '描述',
  KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT  INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES 
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');

基本环境搭建

1、新建一Maven项目!ssmbuild , 添加web的支持

2、导入相关的pom依赖!

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.19.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.16</version>
        </dependency>
<!--        数据库连接池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
<!--        Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>
<!--        Servlet API-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>

3、Maven资源过滤设置

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

4、建立基本结构和配置框架!

  • com.gao.pojo

  • com.gao.mapper

  • com.gao.service

  • com.gao.controller

  • mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
    </configuration>
    
  • applicationContext.xml

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

Mybatis层编写

1、数据库配置文件 database.properties

driver=com.mysql.jdbc.Driver
# 如果使用的是MysQL8.0+,增加一个时区的配置;&serverTimezone=Asia/Shanghai
url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&serverTimezone=UTC
name=root
password=123456

2、编写MyBatis的核心配置文件

<?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>
    <typeAliases>
        <package name="com.gao.pojo"/>
    </typeAliases>
    <mappers>
        <mapper class="com.gao.mapper.BookMapper"/>
    </mappers>
</configuration>

3、编写数据库对应的实体类 com.gao.pojo.Books

使用lombok插件!

package com.kuang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    
    private int id;
    private String name;
    private int count;
    private String detail;
    
}

5、编写Dao层的 Mapper接口!

package com.gao.mapper;

import com.gao.pojo.Books;

import java.util.List;

public interface BookMapper {
    int addBook(Books books);

    int deleteBook(int id);

    int updateBook(Books books);

    Books queryBook(int id);

    List<Books> queryAllBooks();

    Books queryBookByName(String name);
}

6、编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包;

<?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="com.gao.mapper.BookMapper">
    <insert id="addBook" parameterType="Books">
        insert into books (name,count,detail) values (#{name},#{count},#{detail});
    </insert>

    <delete id="deleteBook" parameterType="_int">
        delete from books where id = #{id}
    </delete>

    <update id="updateBook" parameterType="Books">
        update books set name = #{name},count =#{count},detail=#{detail}
        where id = #{id}
    </update>

    <select id="queryBook" resultType="Books">
        select * from books where id = #{id}
    </select>

    <select id="queryAllBooks" resultType="Books">
        select * from books
    </select>

    <select id="queryBookByName" resultType="Books">
        select * from books where name = #{name}
    </select>
</mapper>

7、编写Service层的接口和实现类

接口:

package com.gao.service;


import com.gao.pojo.Books;

import java.util.List;

public interface BookService {
    int addBook(Books books);

    int deleteBook(int id);

    int updateBook(Books books);

    Books queryBook(int id);

    List<Books> queryAllBooks();

    Books queryBookByName(String name);
}

实现类:

package com.gao.service;

import com.gao.mapper.BookMapper;
import com.gao.pojo.Books;

import java.util.List;

public class BookServiceImpl implements BookService{
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    @Override
    public int addBook(Books books) {
        return bookMapper.addBook(books);
    }

    @Override
    public int deleteBook(int id) {
        return bookMapper.deleteBook(id);
    }

    @Override
    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }

    @Override
    public Books queryBook(int id) {
        return bookMapper.queryBook(id);
    }

    @Override
    public List<Books> queryAllBooks() {
        return bookMapper.queryAllBooks();
    }

    @Override
    public Books queryBookByName(String name) {
        return bookMapper.queryBookByName(name);
    }
}

OK,到此,底层需求操作编写完毕!

Spring层

1、配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;

2、我们去编写Spring整合Mybatis的相关的配置文件;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="${driver}"/>
        <property name="jdbcUrl" value="${url}"/>
        <property name="user" value="${name}"/>
        <property name="password" value="${password}"/>

        <!--c3p0连接池的私有属性-->
        <property name="maxPoolSize" value="30"/><property name="minPoolSize" value="10"/>
        <!--关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false" />
        <!--获取连接超时时问-->
        <property name="checkoutTimeout" value="1080"/>
        <!--当获取连接失败重试次数-->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>
<!--3、sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

<!--4、配置dao扫描包,动态的实现Mapper接口可以注入到Spring中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--        要扫描的mapper包-->
        <property name="basePackage" value="com.gao.mapper"/>
    </bean>
</beans>

3、Spring整合service层

<?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、扫描service下的包-->
    <context:component-scan base-package="com.gao.service"/>

<!--    2、将我们的所有业务类,注入到Spring中,可以通过配置或者注解实现-->
    <bean id="bookServiceImpl" class="com.gao.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>
<!--    3、声明式事务配置-->
    <bean id="transactionManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--        注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

Spring层搞定!再次理解一下,Spring就是一个大杂烩,一个容器!

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">
<!--    DispatcherServlet-->
    <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:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</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-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

2、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
       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/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--    1、注解驱动-->
    <mvc:annotation-driven/>
<!--    2、静态资源过滤-->
    <mvc:default-servlet-handler/>
<!--    3、扫描包-->
    <context:component-scan base-package="com.gao.controller"/>
<!--    4、视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3、Spring配置整合文件,applicationContext.xml

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

</beans>

配置文件,暂时结束!Controller 和 视图层编写

1、BookController 类编写 , 方法一:查询全部书籍

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBooks();
        model.addAttribute("list",list);
        return "allBook";
    }
}

2、编写首页 index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <style>
      a{
        text-decoration: none;
        color: black;
        font-size: 18px;
      }
      h3{
        width: 180px;
        height: 38px;
        margin: 350px auto;
        text-align: center;
        line-height: 38px;
        background: deepskyblue;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
  <h3>
    <a href="${pageContext.request.contextPath}/book/allBook">进入书籍展示界面</a>
  </h3>
  </body>
</html>

3、书籍列表页面 allbook.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍展示界面</title>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row ui-helper-clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>书籍列表————————显示书籍</small>
                </h1>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a>
        </div>
        <div class="col-md-4 column"></div>
        <div class="col-md-4 column">
            <span style="color: red;font-weight: bold">${error}</span>
            <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBookByName" method="post" style="float: right">
                <input type="text" name="queryName" class="form-control" placeholder="请输入要查询的书籍名称">
                <input type="submit" value="查询" class="btn btn-primary">
            </form>
        </div>
    </div>

    <div class="row ui-helper-clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <th>书籍编号</th>
                <th>书籍名称</th>
                <th>书籍数量</th>
                <th>书籍详情</th>
                </thead>
                <tbody>
                <c:forEach var="book" items="${list}">
                    <tr>
                        <td>${book.id}</td>
                        <td>${book.name}</td>
                        <td>${book.count}</td>
                        <td>${book.detail}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.getId()}">修改</a> |
                            <a href="${pageContext.request.contextPath}/book/deleteBook/${book.getId()}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>

4、BookController 类编写 , 方法二:添加书籍

    @RequestMapping("/toAddBook")
    public String toAddBooks(){
        return "addBook";
    }

    @RequestMapping("/addBook")
    public String addBook(Books books){
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

5、添加书籍页面:addBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>新增书籍</title>
    
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</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>
    <form action="${pageContext.request.contextPath}/book/addBook" method="post">
        书籍名称:<input type="text" class="form-control" name="name" required><br><br><br>
        书籍数量:<input type="text" class="form-control" name="count" required><br><br><br>
        书籍详情:<input type="text" class="form-control" name="detail" required><br><br><br>
        <input type="submit" value="添加">
    </form>

</div>
</body>
</html>

6、BookController 类编写 , 方法三:修改书籍

    @RequestMapping("/toUpdate")
    public String toUpdateBook(int id,Model model){
        Books books = bookService.queryBook(id);
        model.addAttribute("QBook",books);
        return "updateBook";
    }
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

7、修改书籍页面 updateBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改界面</title>
    
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</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>
    <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
        <input type="hidden" name="id" value="${QBook.id}">
        书籍名称:<input type="text" class="form-control" name="name" value="${QBook.name}" required><br><br><br>
        书籍数量:<input type="text" class="form-control" name="count" value="${QBook.count}" required><br><br><br>
        书籍详情:<input type="text" class="form-control" name="detail" value="${QBook.detail}" required><br><br><br>
        <input type="submit" value="修改">
    </form>

</div>
</body>
</html>

8、BookController 类编写 , 方法四:删除书籍

    @RequestMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable("id") int id){
        bookService.deleteBook(id);
        return "redirect:/book/allBook";
    }

进行功能拓展:搜索功能

注意,在进行拓展时一定要从底层开始写起(底层代码和jsp代码已经粘贴在了上面)

BookController 类编写

@RequestMapping("/queryBookByName")
public String queryBookByName(String queryName,Model model){
    Books books = bookService.queryBookByName(queryName);
    List<Books> list = new ArrayList<Books>();
    list.add(books);
    if (books==null){
        list =bookService.queryAllBooks();
        model.addAttribute("error","未查询到书籍");
    }
    model.addAttribute("list",list);
    return "allBook";
}

遇见的问题;

  • 导入依赖时,一定要确保依赖的正确性,如:

    • javax.servlet.jsp.jstl 和 jstl,当导入第一个时包时,web项目运行时就会报错
  • 在进行spring-mvc.xml的视图解析器的配置时,注意/WEB-INF和WEB-INF的区别

    • 不加 / 的WEB-INF他是跳转到和自己同级目录下的页面。
      /,的话他会跳转到整个网站的根目录下,如果在自己电脑上测试的的话,就是跳转到http://localhost:8080/
    • 这取决于你在class外部加没加@RequestMapping,如果加了代表有两层,需要用/WEB-INF,如果没加,一层就用WEB-INF
  • MysQL8.0+,配置文件的url中要增加一个时区的配置

  • 页面的加载有时会报500的异常错误:

  • org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
    ### Error querying database.  Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: An attempt by a client to checkout a Connection has timed out
    
  • 如果确定时区的配置没有问题,刷新页面即可

  • 建完项目,导完包后,要手动建立ArtiFacts中WEB-INF下建立lib文件添加依赖

要点:

  • 熟悉ssm的框架搭建和相关配置
  • 对于功能的拓展要从底层开始实现
  • 掌握页面间的跳转和controller,jsp之间的关联
这篇关于SSM整合的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!