SpringMVC-ssm整合

SSM整合

环境要求:

  • IDEA
  • MySQL 5.7.19
  • Tomcat 9.0.41
  • Maven 3.6

数据库环境

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
PRIMARY 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.导入相关依赖

    <!--1.导包junit,数据库驱动,mybatis,spring-webmvc,spring-jdbc,servlet,jsp-->
    <dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!--Servlet - JSP -->
        <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</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>

    </dependencies>

3.maven资源过滤设置

    <!--2.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.建立基本结构和配置框架!

  • com.kuang.pojo
  • com.kuang.dao
  • com.kuang.service
  • com.kuang.controller

Mybatis层编写
1.创建数据库配置文件 database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

2.创建mybatis核心配置文件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>

    <!--日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--别名-->
    <typeAliases>
        <package name="com.kuang.pojo"/>
    </typeAliases>

    <!--映射-->
    <mappers>
        <mapper class="com.kuang.dao.BookMapper"/>
    </mappers>
</configuration>

3.创建实体类Books

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    
    
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

4.编写Dao层的 Mapper接口!

public interface BookMapper {
    
    

    //插入一本书
    int insertBook(Books books);

    //删除一本书
    int deleteBook(@Param("id") int id);

    //更新一本书
    int updateBook(Books books);

    //查询一本书
    Books queryBooks(@Param("id") int id);

    //查询所有书
    List<Books> queryAllBooks();

    //根据书名查询
    Books queryBooksByName(@Param("name") String name);
}

5.编写接口对应的 Mapper.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="com.kuang.dao.BookMapper">

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

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

    <update id="updateBook" parameterType="books">
        update books set bookName = #{bookName} ,bookCounts=#{bookCounts},detail=#{detail}
        where bookID=#{bookID};
    </update>
    
    <select id="queryBooks" resultType="books">
        select * from books where bookID=#{id};
    </select>
    
    <select id="queryAllBooks" resultType="books">
        select * from books;
    </select>

    <select id="queryBooksByName" resultType="books">
        select * from books where bookName=#{name};
    </select>
</mapper>

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

public class BookServiceImpl implements BookService{
    
    

    private BookMapper bookMapper;

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

    public int insertBook(Books books) {
    
    
        return bookMapper.insertBook(books);
    }

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

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

    public Books queryBooks(int id) {
    
    
        return bookMapper.queryBooks(id);
    }

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

    public Books queryBooksByName(String name) {
    
    
        return bookMapper.queryBooksByName(name);
    }
}

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

Spring层
1.首先配置Spring整合MyBatis,我们这里数据源使用c3p0连接池,编写Spring整合Mybatis的相关的配置文件;spring-dao.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
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!--1.关联数据库文件-->
    <context:property-placeholder location="classpath:database.properties"/>

    <!--2.配置数据源-->
    <!--数据库连接池
    c3p0 自动化操作(自动的加载配置文件,并且设置到对象里)
    -->
    <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"/>
    </bean>

    <!--4.配置扫描Dao接口包,动态实现Dao接口注入到Spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入sqlSessionFactory,可省?一套dataSource可省,多套不可省!-->
<!--        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>-->
        <!--给出需要扫描的Dao接口包-->
        <property name="basePackage" value="com.kuang.dao"/>
    </bean>
</beans>

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"
       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">

    <!--1.扫描service层的注解-->
    <context:component-scan base-package="com.kuang.service"/>

    <!--2.BookServiceImpl注入容器-->
    <bean id="bookServiceImpl" class="com.kuang.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

    <!--3.配置事务管理器-->
    <bean id="transactionManager" 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>encoding</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>encoding</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
   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
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--1.开启SpringMVC注解驱动-->
    <mvc:annotation-driven/>

    <!--2.静态资源过滤-->
    <mvc:default-servlet-handler/>

    <!--3.配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--4.扫描controller层的注解-->
    <context:component-scan base-package="com.kuang.controller"/>

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

    <import resource="spring-dao.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 language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
  <title>首页</title>
  <style type="text/css">
    a {
    
    
      text-decoration: none;
      color: black;
      font-size: 18px;
    }
    h3 {
    
    
      width: 180px;
      height: 38px;
      margin: 100px auto;
      text-align: center;
      line-height: 38px;
      background: deepskyblue;
      border-radius: 4px;
    }
  </style>
</head>
<body>

<h3>
  <%--
  ${
    
    pageContext.request.contextPath}等价于<%=request.getContextPath()%>
  二者都是获取项目名(上下文),本项目中获取的是:/ssmbuild
  --%>
  <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>
    <!-- 引入 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>

    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
        </div>
        <div class="col-md-4 column">
        </div>
        <div class="col-md-4 column">
            <form action="/book/queryBook" method="post">
                <input type="text" name="booksName">
                <input type="submit" class="btn btn-primary" value="查询">
            </form>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>书籍编号</th>
                    <th>书籍名字</th>
                    <th>书籍数量</th>
                    <th>书籍详情</th>
                    <th>操作</th>
                </tr>
                </thead>

                <tbody>
                <c:forEach var="book" items="${list}">
                    <tr>
                        <td>${
    
    book.getBookID()}</td>
                        <td>${
    
    book.getBookName()}</td>
                        <td>${
    
    book.getBookCounts()}</td>
                        <td>${
    
    book.getDetail()}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/book/toUpdateBook?bookId=${book.getBookID()}">更改</a> |
                            <a href="${pageContext.request.contextPath}/book/deleteBook/${book.getBookID()}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

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

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

    @RequestMapping("/addBook")
    public String addBook(Books books){
    
    
        int i = bookService.insertBook(books);
        if (i>0){
    
    
            System.out.println("插入成功!");
        }
        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" name="bookName"><br><br><br>
            书籍数量:<input type="text" name="bookCounts"><br><br><br>
            书籍详情:<input type="text" name="detail"><br><br><br>
            <input type="submit" value="添加">
        </form>

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

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

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(@RequestParam("bookId") int id,Model model){
    
    
        Books book = bookService.queryBooks(id);
        model.addAttribute("book",book);
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Books books){
    
    
        int i = bookService.updateBook(books);
        if (i>0){
    
    
            System.out.println("修改成功!");
        }
        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="bookID" value="${book.getBookID()}">
            书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"><br><br><br>
            书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"><br><br><br>
            书籍详情:<input type="text" name="detail" value="${book.getDetail()}"><br><br><br>
            <input type="submit" value="添加">
        </form>

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

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

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

9.BookController 类编写 , 方法五:查询书籍

    @RequestMapping("/queryBook")
    public String queryBookByName(@RequestParam("booksName") String name,Model model){
    
    
        Books books = bookService.queryBooksByName(name);
        //System.err.println("books");
        List<Books> list=new ArrayList();
        if (books!=null){
    
    
            list.add(books);
        }else{
    
    
            list = bookService.queryAllBooks();
        }
        model.addAttribute("list",list);
        return "allBook";
    }

10.项目截图
在这里插入图片描述

配置Tomcat,进行运行!

项目结构图
在这里插入图片描述
自己遇到的坑:
问题1:org.apache.jasper.JasperException: /WEB-INF/jsp/allBook.jsp (行.: [42], 列: [16]) 根据标记文件中的TLD或attribute指令,attribute[items]不接受任何表达式
解决:jsp中导入<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
而不是<%@ taglib prefix=“c” uri=“http://java.sun.com/jstl/core” %>

问题2:java.sql.SQLException: Column count doesn’t match value count at row 1
解决:insert into books(bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail});
而不是insert into books values (#{bookName},#{bookCounts},#{detail});

猜你喜欢

转载自blog.csdn.net/qq_42665745/article/details/113144811