springMVC基础3(项目整合mybatis)

1、目录结构

2、pojo

​ 书籍的属性。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookId;
    private String bookName;
    private int bookCount;
    private String detail;
}

3、Dao(mapper)

​ 负责直接和数据库交互。

public interface BookMapper {
   int addBook(Books book);
   int deleteBookById(@Param("bookId") int bookId);
   int updateBook(Books book);
   Books selectBookById(@Param("bookId") int bookId);
   List<Books> selectBookByName(@Param("bookName") String bookName);
   List<Books> selectAllBooks();
}

4、Service

​ 负责处理业务同时调用dao层,虽然大部分只有调用dao层但是还有要有。

public interface BookService {
    int addBook(Books book);
    int deleteBookById(int bookId);
    int updateBook(Books book);
    Books selectBookById(int bookId);
    List<Books> selectAllBooks();
    List<Books> selectBookByName(String bookName);
}
public class BookServiceImpl implements BookService{
//    service调用dao层
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }
    @Override
    public int addBook(Books book) {
        return bookMapper.addBook(book);
    }
    @Override
    public int deleteBookById(int bookId) {
        return bookMapper.deleteBookById(bookId);
    }
    @Override
    public int updateBook(Books book) {
        return bookMapper.updateBook(book);
    }
    @Override
    public Books selectBookById(int bookId) {
        return bookMapper.selectBookById(bookId);
    }
    @Override
    public List<Books> selectAllBooks() {
        return bookMapper.selectAllBooks();
    }
    @Override
    public List<Books> selectBookByName(String bookName) {
        return bookMapper.selectBookByName(bookName);
    }
}

5、Controller

​ 负责视图跳转和调用service层,负责跳转页面的逻辑可以在传递过程加一些参数。

@Controller
@RequestMapping(value = "/book")
//controller层调用service层
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    BookService bookService;
//    读取数据库信息,跳转到展示书籍信息界面
    @RequestMapping(value = "/allBooks")
    public String allBooks(Model model){
        List<Books> books = bookService.selectAllBooks();
        model.addAttribute("allBooks",books);
        return "allBooks";
    }
//    跳转到添加书籍的表单界面
    @RequestMapping(value = "/toAddPage")
    public String toAddPage(){
        return "addBook";
    }
//    添加书籍,复用public String allBooks(Model model),重定向到/book/allBooks
    @RequestMapping("/addBook")
    public String addBook(Books book){
        bookService.addBook(book);
        return "redirect:/book/allBooks";
    }
//    跳转到修改界面
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(int id,Model model){
        Books book = bookService.selectBookById(id);
        model.addAttribute("book",book);
        return "updateBook";
    }
    //    修改书籍,复用public String allBooks(Model model),重定向到/book/allBooks
    @RequestMapping("/updateBook")
    public String updateBook(Books book){

        bookService.updateBook(book);
        return "redirect:/book/allBooks";
    }
    //    跳转到删除界面
    @RequestMapping("/toDeleteBook/{bookId}")
    public String toDeleteBook(@PathVariable("bookId") int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBooks";
    }
//    查询书籍
    @RequestMapping("/queryBookByName")
    public String queryBookByName(String queryBookName,Model model){
        List<Books> books = bookService.selectBookByName(queryBookName);
        if(books.size()==0){
            books = bookService.selectAllBooks();
            model.addAttribute("error","没有查询寻到书籍!");
        }
        model.addAttribute("allBooks",books);
        return "allBooks";
    }
}

6、数据库表

7、pom.xml

​ 使用c3p0连接池。

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>com.zhangxin.ssmbuild</groupId>  
  <artifactId>SSMBuild</artifactId>  
  <version>1.0-SNAPSHOT</version>  
  <packaging>war</packaging>  
  <properties> 
    <maven.compiler.source>8</maven.compiler.source>  
    <maven.compiler.target>8</maven.compiler.target> 
  </properties>  
  <dependencies> 
    <!--junit-->  
    <dependency> 
      <groupId>junit</groupId>  
      <artifactId>junit</artifactId>  
      <version>4.13.2</version>  
      <scope>test</scope> 
    </dependency>  
    <!--        数据库驱动-->  
    <dependency> 
      <groupId>mysql</groupId>  
      <artifactId>mysql-connector-java</artifactId>  
      <version>8.0.28</version> 
    </dependency>  
    <!--        数据库连接池-->  
    <dependency> 
      <groupId>com.mchange</groupId>  
      <artifactId>c3p0</artifactId>  
      <version>0.9.5.5</version> 
    </dependency>  
    <!--servlet JSP-->  
    <dependency> 
      <groupId>javax.servlet</groupId>  
      <artifactId>servlet-api</artifactId>  
      <version>2.5</version> 
    </dependency>  
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->  
    <dependency> 
      <groupId>javax.servlet.jsp</groupId>  
      <artifactId>jsp-api</artifactId>  
      <version>2.2.1-b03</version>  
      <scope>provided</scope> 
    </dependency>  
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->  
    <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.7</version> 
    </dependency>  
    <dependency> 
      <groupId>org.mybatis</groupId>  
      <artifactId>mybatis-spring</artifactId>  
      <version>2.0.6</version> 
    </dependency>  
    <!--        spring-->  
    <dependency> 
      <groupId>org.springframework</groupId>  
      <artifactId>spring-webmvc</artifactId>  
      <version>5.3.15</version> 
    </dependency>  
    <dependency> 
      <groupId>org.springframework</groupId>  
      <artifactId>spring-jdbc</artifactId>  
      <version>5.3.24</version> 
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.21</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.30</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <!--    静态资源过滤-->  
  <build> 
    <resources> 
      <resource> 
        <directory>src/main/java</directory>  
        <includes> 
          <include>**/*.properties</include>  
          <include>**/*.xml</include> 
        </includes>  
        <filtering>true</filtering> 
      </resource>  
      <resource> 
        <directory>src/main/resources</directory>  
        <includes> 
          <include>**/*.properties</include>  
          <include>**/*.xml</include> 
        </includes>  
        <filtering>true</filtering> 
      </resource> 
    </resources> 
  </build> 
</project>

8、JDBC资源文件

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_build?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=1234567

9、MyBatis配置xml

​ 由于数据库采用下划线命名而java对应的类是驼峰命名,所以当执行select语句时查询出来的结果名字(列名)无法和java类的属性映射,因此需要< setting name=“mapUnderscoreToCamelCase” value=“true”/>转化成驼峰命名。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--    配置信息文件-->
    <properties resource="jdbc.properties"/>
    <settings>
        <!--    数据库中的下滑线命名转换成java的驼峰命名-->
        <setting  name="mapUnderscoreToCamelCase"  value="true"/>
<!--        日志·-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--    设置类型别名 不区分大小写-->
    <typeAliases>
<!--        <typeAlias type="" alias=""/>-->
        <!--        引入一个包的类型别名,默认是全部包名下的类的名字是别名-->
                <package name="com.zhangxin.pojo"/>
    </typeAliases>
    <!--引入映射文件-->
    <mappers>
        <!--        <mapper resource="mappers/UserMapper.xml"/>-->
        <!--        引入整个包,需要目录结构目录名字,文件名和相关接口所在的包名一致-->
<!--        <package name="com....."/>-->
        <mapper class="com.zhangxin.dao.BookMapper"/>
    </mappers>
</configuration>

10、spring-dao.xml

​ 主要工作是配置数据库和把dao层注入spring容器托管。

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

<context:annotation-config/>
    <!--             引入数据库配置文件-->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties"/>
    <!--       配置数据源(连接池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}"/>
    </bean>
    <!--      定义 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容器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--        要扫描的包-->
        <property name="basePackage" value="com.zhangxin.dao"/>
        <!--        注入 sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

11、spring-service.xml

​ 主要工作是配置声明式事务管理器和把service层注入spring容器托管。

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

    <context:annotation-config/>
       <!--自动扫描包,使得此包下的所有注解生效-->
       <context:component-scan base-package="com.zhangxin.service"/>
<!--注入所有service类-->
    <bean id="BookServiceImpl" class="com.zhangxin.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>
    <!-- 配置声明式事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

12、spring-mvc.xml

​ 主要工作是配置视图解析器和把controller层注入spring容器托管。

<?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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config/>
    <!--自动扫描包,使得此包下的所有注解生效-->
    <context:component-scan base-package="com.zhangxin.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>

13、ApplicationContext.xml

​ 整合spring配置文件

<?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">
    <context:annotation-config/>
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>
</beans>

14、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app
	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">

	<!--配置springmvc核心,前端控制器-->
	<!--	所有的请求都会转发至此-->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!--		绑定spring的配置文件-->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:ApplicationContext.xml</param-value>
		</init-param>
		<!--		设置启动级别为1,和服务器一起启动-->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!--	springmvc的过滤器,防止中文乱码--><!--SpringMVC中提供的字符编码过滤器,放在所有过滤器的最上方-->
	<filter>
		<filter-name>encFilter</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>encFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

15、jsp页面

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <h3>
        <a href="${pageContext.request.contextPath}/book/allBooks">跳转到所有书籍</a>
    </h3>

</body>
</html>

addBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>addBook-</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 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">
        <div class="form-group">
            <label for="aa">书籍名称:</label>
            <input type="text" class="form-control" id="aa" name="bookName" required>
        </div>
        <div class="form-group">
            <label for="bb">书籍数量:</label>
            <input type="text" class="form-control" id="bb" name="bookCount" required>
        </div>
        <div class="form-group">
            <label for="cc">书籍描述:</label>
            <input type="text" class="form-control" id="cc" name="detail" required>
        </div>
        <button type="submit" class="btn btn-primary">添加书籍</button>
    </form>

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

allBooks.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>allBooks</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 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/toAddPage">新增书籍</a>
                    <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBooks">全部书籍</a>
                </div>
                <div class="col-md-4 column"></div>
                <div class="col-md-4 column" >
                    <form action="${pageContext.request.contextPath}/book/queryBookByName" method="post" class="form-inline">
                        <input type="text" name="queryBookName" class="form-control" placeholder="请输入查询的书籍名称" >
                        <input type="submit" value="查询" class="btn btn-primary">
                    </form>
                </div>
            </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="${allBooks}">
                            <tr>
                                <td>${book.bookId}</td>
                                <td>${book.bookName}</td>
                                <td>${book.bookCount}</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/toDeleteBook/${book.bookId}">删除</a>
                                </td>
                            </tr>
                        </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>

    </div>

</body>
</html>

updateBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>updateBook</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 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">
        <div class="form-group">
            <label for="aa">书籍名称:</label>
            <input type="text" class="form-control" id="aa" name="bookName" value="${book.bookName}" required>
        </div>
        <div class="form-group">
            <label for="bb">书籍数量:</label>
            <input type="text" class="form-control" id="bb" name="bookCount" value=${book.bookCount} required>
        </div>
        <div class="form-group">
            <label for="cc">书籍描述:</label>
            <input type="text" class="form-control" id="cc" name="detail" value=${book.detail} required>
        </div>
        <button type="submit" class="btn btn-primary">修改书籍</button>
        <input type="hidden" name="bookId" value="${book.bookId}">
    </form>

</div>
</body>
</html>
  • 27
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值