SpringMVC(六):分层整合SSM

本文是按照狂神说的教学视频学习的笔记,强力推荐,教学深入浅出一遍就懂!b站搜索狂神说或点击下面链接

https://space.bilibili.com/95256449?spm_id_from=333.788.b_765f7570696e666f.2

 

源码已上传github:https://github.com/renzhongpei/ssmbuilder

 

环境搭建

  • 版本:

    • MySQL 8

    • SpringMVC+Spring+Mybatis

    • C3P0连接池

数据库建表

CREATE DATABASE `ssmbuild`;
`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 '描述',
  KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
​
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删1库到跑路'),
(3,'Linux',5,'从进门到进牢');

 


项目搭建

创建maven项目

1.pom.xml

  • 导入依赖

  • 静态资源发布管理(build)

    <!--导入依赖-->
    <dependencies>
        <!--jackson-->
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.3</version>
        </dependency>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <!--spring connect to db-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <!--aop-->
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.4</version>
        </dependency>
        <!--Mybatis and spring -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!--servlet依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <!--jsp依赖-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
        </dependency>
        <!--jstl表达式-->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
        <!--standard标签库-->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!--log4j日志-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.3</version>
        </dependency>
        <!--工具类,可以复制对象-->
        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <!--resources其实可以不配,因为会自动打包-->
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <!--java下配置了properties文件就能自动打包-->
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

 


2.建立基本框架

  • 建立4个空的包和database.properties文件

 

 

 

  • database.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3308/ssmbuild?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=mysql

 

整合Mybatis

 

 

 

Books

package com.rzp.pojo;
​
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
​
    @Override
    public String toString() {
        return "Books{" +
                "bookID=" + bookID +
                ", bookName='" + bookName + '\'' +
                ", bookCounts=" + bookCounts +
                ", detail='" + detail + '\'' +
                '}';
    }
​
    public Books() {
    }
​
    public Books(int bookID, String bookName, int bookCounts, String detail) {
        this.bookID = bookID;
        this.bookName = bookName;
        this.bookCounts = bookCounts;
        this.detail = detail;
    }
​
    public int getBookID() {
        return bookID;
    }
​
    public void setBookID(int bookID) {
        this.bookID = bookID;
    }
​
    public String getBookName() {
        return bookName;
    }
​
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
​
    public int getBookCounts() {
        return bookCounts;
    }
​
    public void setBookCounts(int bookCounts) {
        this.bookCounts = bookCounts;
    }
​
    public String getDetail() {
        return detail;
    }
​
    public void setDetail(String detail) {
        this.detail = detail;
    }
}
​

 

BookMapper接口

package com.rzp.dao;
​
import com.rzp.pojo.Books;
import org.apache.ibatis.annotations.Param;
​
import java.util.List;
​
public interface BookMapper {
    void addBook(Books book);
    void deleteBookById(@Param("bookId") int id);
    void updateBook(Books book);
    Books queryBookById(@Param("bookId") int id);
    List<Books> queryAllBook();
    List<Books> searchBook(@Param("bookName") String bookName);
}
​

 

BookMapper.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.rzp.dao.BookMapper">
    <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" parameterType="_int" resultType="Books">
        select * from books where bookID = #{bookId}
    </select><select id="queryAllBook" resultType="Books">
        select * from books
    </select><select id="searchBook" resultType="Books">
        select * from books where bookName like "%"#{bookName}"%"
    </select>
</mapper>

 

BookService接口

package com.rzp.service;
​
import com.rzp.pojo.Books;
import org.apache.ibatis.annotations.Param;
​
import java.util.List;
​
public interface BookService {
​
    void addBook(Books book);
    void deleteBookById(int id);
    void updateBook(Books book);
    Books queryBookById(int id);
    List<Books> queryAllBook();
    List<Books> searchBook(@Param("bookName") String bookName);
​
}
​

 

BookService实现类

package com.rzp.service;
​
import com.rzp.dao.BookMapper;
import com.rzp.pojo.Books;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
​
import java.util.List;
​
@Service
public class BookServiceImpl implements BookService{
    //Service调用dao层,因此要组合Dao
    @Autowired
    private BookMapper bookMapper;
​
    public BookMapper getBookMapper() {
        return bookMapper;
    }
​
    public void setBookMapper(BookMapper bookMapper) {
        bookMapper = bookMapper;
    }
​
    @Override
    public void addBook(Books book) {
        bookMapper.addBook(book);
    }
​
    @Override
    public void deleteBookById(int id) {
        bookMapper.deleteBookById(id);
    }
​
    @Override
    public void updateBook(Books book) {
        bookMapper.updateBook(book);
    }
​
    @Override
    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }
​
    @Override
    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }
​
    @Override
    public List<Books> searchBook(String bookName) {
        return bookMapper.searchBook(bookName);
    }
}
​

 

mybatis主配置文件注册mapper

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

 

log4J

  • 使用Mybatis官方提供的配置

 

 

 

# 全局日志配置
log4j.rootLogger=ERROR, stdout
# MyBatis 日志配置
log4j.logger.com.rzp.dao=TRACE
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

 

 

整合Spring层

  • 增加两个配置文件,并且注入到applicationContext.xml中,使Spring的配置文件关联起来。

    • Spring-dao.xml :这个文件其实就是Spring-整合Mybatis后的Spring数据库连接配置文件,替代了Mybatis主配置文件中的数据库连接的配置。

    • Spring-service.xml :这个专门用作service的注册

 

 

 

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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-tool.xsd">
    <!--1.关联数据库配置文件-->
    <context:property-placeholder location="classpath:database.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"/>
    </bean><!--配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
    <!--解释 : https://www.cnblogs.com/jpfss/p/7799806.html-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入SqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--要扫描的Dao包-->
        <property name="basePackage" value="com.rzp.dao"/>
    </bean>
    <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <constructor-arg ref="dataSource" />
    </bean>
    <!--结合AOP实现事务的植入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--propagation事务的传播特性,默认Required-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice><aop:config>
        <!--通过aop代理启动事务,注明哪个包需要添加事务-->
        <aop:pointcut id="txPoint" expression="execution(* com.rzp.dao..*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>
</beans>

 

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"
       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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--扫描service下的包,读取该包下的注解-->
    <context:component-scan base-package="com.rzp.service"/>
​
​
​
    <!--讲所有业务类注入到spring,可以通过配置或者注解实现-->
    <bean id = "BookServiceImpl" class="com.rzp.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean></beans>

 

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-tool.xsd">
    <!--扫描service下的包,读取该包下的注解-->
    <context:component-scan base-package="com.rzp.service"/><!--讲所有业务类注入到spring,可以通过配置或者注解实现-->
    <bean id = "BookServiceImpl" class="com.rzp.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean></beans>

 

整合SpringMVC层

  • 添加web框架和spring-mvc.xml,并把spring-mvc.xml注入到applicationContext.xml中。

    • spring-mvc:注册视图解析器,Controller层的注解扫描。

 

 

 

web框架

  • 使用IDEA自带功能添加即可

 

 

 

 

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>CharacterEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
​
    <!--session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

 

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

 

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--导入所有spring的配置文件-->
    <import resource="classpath:spring-service.xml"/>
    <import resource="spring-dao.xml"/>
    <import resource="spring-mvc.xml"/></beans>

 

  • 最后建立jsp文件夹

 

 

 

编写Controller层测试

  • 首先添加Tomcat发布时把jar包发布到项目中的设置

 

 

 

 

 

 

 

 

 

 

 

 

这样就会把依赖的jar包发布到项目中。

  • SysInfo

    • pojo包下添加SysInfo类,方便页面传参数

package com.rzp.pojo;
​
public class SysInfo {
    private String infoStr1;
    private String infoStr2;
    private String infoStr3;
    private Double infoDou1;
    private Double infoDou2;
    private Double infoDou3;
    public SysInfo() {
        this.infoDou1 = 0d;
        this.infoDou2 = 0d;
        this.infoDou3 = 0d;
    }
​
    @Override
    public String toString() {
        return "SysInfo{" +
                "infoStr1='" + infoStr1 + '\'' +
                ", infoStr2='" + infoStr2 + '\'' +
                ", infoStr3='" + infoStr3 + '\'' +
                ", infoDou1=" + infoDou1 +
                ", infoDou2=" + infoDou2 +
                ", infoDou3=" + infoDou3 +
                '}';
    }
​
    public String getInfoStr1() {
        return infoStr1;
    }
​
    public void setInfoStr1(String infoStr1) {
        this.infoStr1 = infoStr1;
    }
​
    public String getInfoStr2() {
        return infoStr2;
    }
​
    public void setInfoStr2(String infoStr2) {
        this.infoStr2 = infoStr2;
    }
​
    public String getInfoStr3() {
        return infoStr3;
    }
​
    public void setInfoStr3(String infoStr3) {
        this.infoStr3 = infoStr3;
    }
​
    public Double getInfoDou1() {
        return infoDou1;
    }
​
    public void setInfoDou1(Double infoDou1) {
        this.infoDou1 = infoDou1;
    }
​
    public Double getInfoDou2() {
        return infoDou2;
    }
​
    public void setInfoDou2(Double infoDou2) {
        this.infoDou2 = infoDou2;
    }
​
    public Double getInfoDou3() {
        return infoDou3;
    }
​
    public void setInfoDou3(Double infoDou3) {
        this.infoDou3 = infoDou3;
    }
​
​
}

 

  • BookController

package com.rzp.controller;
​
import com.rzp.pojo.Books;
import com.rzp.pojo.SysInfo;
import com.rzp.service.BookService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
​
import javax.servlet.http.HttpServletRequest;
import java.util.List;
​
@Controller
@RequestMapping("/book")
public class BookController {
    //Controller调Sercice层
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;
​
    //查询全部books并且返回到books展示页面
    @RequestMapping("/allBook")
    public String listBooks(Model model){
        List<Books> booksList = bookService.queryAllBook();
        model.addAttribute("list",booksList);
        return "allBook";
    }
​
    //跳转到增加书籍界面
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }
​
    //添加书籍请求
    @RequestMapping("/AddingBook")
    public String addBook(Books books){
        System.out.println("addBook="+books);
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }
​
    //跳转到修改书籍界面
    @RequestMapping("/toUpdateBook")
    public String toUpdatePaper(int id,Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("Qbooks",books);
        return "updateBook";
    }
​
    //修改书籍请求
    @RequestMapping("/updatingBook")
    public String updateBook(Books books){
        System.out.println("UpdatingBook="+books);
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }
​
    //删除书籍
    @RequestMapping("/deleteBook/{id}")
    public String deleteBook(@PathVariable("id") int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }
​
    //搜索书籍
    @RequestMapping("/searchBook")
    public String searchBook(SysInfo sysInfo,Model model){
        if (sysInfo.getInfoStr1()!=null&&!"".equals(sysInfo.getInfoStr1())){
            List<Books> booksList = bookService.searchBook(sysInfo.getInfoStr1());
            model.addAttribute("list",booksList);
        }else {
            model.addAttribute("msg","请输入要查询的数据");
        }
        return "allBook";
    }
}

 

  • 页面

 

 

 

  • addBook


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>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/AddingBook" method="post">
        <div class="form-group">
            <label>书籍名称</label>
            <input name = "bookName" class="form-control" required>
        </div>
        <div class="form-group">
            <label>书籍数量</label>
            <input name = "bookCounts" class="form-control" required>
        </div>
        <div class="form-group">
            <label>书籍描述</label>
            <input name = "detail" class="form-control" required>
        </div>
        <div class="form-group">
            <input type="submit" class="form-control" value="添加">
        </div>
    </form>
</div>
</body>
</html>

 


  • allBook

<%@ 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 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">
                <form class="form-inline" action="${pageContext.request.contextPath}/book/searchBook" method="get">
                    <input type="text" name="infoStr1" class="form-control" placeholder="请输入要查询的书籍名称">&nbsp;&nbsp;
                    <input type="submit" class="btn btn-primary" value="查询">&nbsp;&nbsp;
                    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">全部书籍</a>
                </form>
            </div>
        </div>
        <div>
            ${msg}
        </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.bookID}</td>
                            <td>${book.bookName}</td>
                            <td>${book.bookCounts}</td>
                            <td>${book.detail}</td>
                            <td>
                                <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.bookID}">修改</a>
                                &nbsp; | &nbsp;
                                <a  href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
                            </td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
​
​
</div>
</body>
</html>

 

  • updateBook

<%@ 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/updatingBook" method="post">

        <input type="hidden"name="bookID" value="${Qbooks.bookID}">
        <div class="form-group">
            <label>书籍名称</label>
            <input name = "bookName" class="form-control" value="${Qbooks.bookName}" required>
        </div>
        <div class="form-group">
            <label>书籍数量</label>
            <input name = "bookCounts" class="form-control" value="${Qbooks.bookCounts}"required>
        </div>
        <div class="form-group">
            <label>书籍描述</label>
            <input name = "detail"  class="form-control" value="${Qbooks.detail}"required>
        </div>
        <div class="form-group">
            <input type="submit" class="form-control" value="修改">
        </div>
    </form>
</div>
</body>
</html>

 



  • index

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

 


  • 测试

    • 满足了最简单的CRUD

 

 

 

posted @ 2020-04-13 20:41  renzhongpei  阅读(180)  评论(0编辑  收藏  举报