ssm整合

图书管理

Books实体类:

package com.itcast.pojo;

public class Books {
     
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String 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;
    }

    @Override
    public String toString() {
     
        return "Books{" +
                "bookID=" + bookID +
                ", bookName='" + bookName + '\'' +
                ", bookCounts=" + bookCounts +
                ", detail='" + detail + '\'' +
                '}';
    }
}

导入依赖

pom.xml:


<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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>ssmartifactId>
    <version>1.0-SNAPSHOTversion>

    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.18version>
        dependency>
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.4version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.6version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.4version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.4version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.2.7.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.2.7.RELEASEversion>
        dependency>
    dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>
project>

数据库

创建数据库、书籍表

CREATE DATABASE ssmbuild;
USE ssmbuild;
CREATE TABLE `books`(
`bookID` INT NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT 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,'从进门到进牢')

dao层

db.properties:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名?userSSl=false&serverTimezome=GMT&useUnicode=true&characterEncoding=utf-8
uname=root
password=123456

Mybatis托管到spring容器中:
spring-dao.xml:


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

    <context:property-placeholder location="classpath:db.properties"/>


    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${driver}"/>
        <property name="jdbcUrl" value="${url}"/>
        <property name="user" value="${uname}"/>
        <property name="password" value="${password}"/>

        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <property name="autoCommitOnClose" value="false"/>
        <property name="checkoutTimeout" value="10000"/>
        <property name="acquireRetryAttempts" value="2"/>
    bean>


    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    bean>


    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>

        <property name="basePackage" value="com.itcast.dao"/>
    bean>
beans>

编写BooksMapper.java接口:

package com.itcast.dao;

import com.itcast.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {
     
//  增加一本书
    public int addBook(Books books);

//  删除一本书
    public int deleteBookByID(@Param("bookID") int id);

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

//  查询一本书
    public Books queryBookByID(@Param("bookID") int id);

//  查询全部书
    public List<Books> queryAllBook();

//  根据书名查找书籍
    public Books queryBooksByName(@Param("bookName") String bookName);
}

实现BooksMapper.xml:




<mapper namespace="com.itcast.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="queryBooksByName" resultType="Books">
        select * from books where bookName = #{bookName};
    select>
mapper>

mybatis-config.xml绑定



<configuration>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>


    <typeAliases>
        <package name="com.itcast.pojo"/>
    typeAliases>

    <mappers>
        <mapper class="com.itcast.dao.BookMapper"/>
    mappers>
configuration>

service层

spring-service.xml:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.itcast.service"/>


    <bean id="BookServiceImpl" class="com.itcast.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    bean>


    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
        
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        tx:attributes>
    tx:advice>

    
    <aop:config>
        <aop:pointcut id="PointCut" expression="execution(* com.itcast.dao.*.*(..))"/>
        <aop:advisor advice-ref="transactionInterceptor" pointcut-ref="PointCut"/>
    aop:config>
beans>

BookService.java接口:

package com.itcast.service;

import com.itcast.pojo.Books;

import java.util.List;

public interface BookService {
     
    //  增加一本书
    public int addBook(Books books);

    //  删除一本书
    public int deleteBookByID(int id);

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

    //  查询一本书
    public Books queryBookByID(int id);

    //  查询全部书
    public List<Books> queryAllBook();

    //  根据书名查找书籍
    public Books queryBooksByName(String bookName);
}

BookServiceImpl:

package com.itcast.service;

import com.itcast.dao.BookMapper;
import com.itcast.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 deleteBookByID(int id) {
     
        return bookMapper.deleteBookByID(id);
    }

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

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

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

    @Override
    public Books queryBooksByName(String bookName) {
     
        return bookMapper.queryBooksByName(bookName);
    }
}

controller层

spring-mvc.xml:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:contect="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">

    
    <contect:component-scan base-package="com.itcast.controller"/>

    
    <mvc:default-servlet-handler/>

    <mvc:annotation-driven/>

    
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>

beans>

大的托管容器applicationContext.xml:


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-mvc.xml"/>
    <import resource="classpath:spring-service.xml"/>

beans>

web.xml:


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:applicationContext.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
    servlet>
    
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <filter>
        <filter-name>encodingfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    <session-config>
        <session-timeout>15session-timeout>
    session-config>
web-app>

BookController.java:

package com.itcast.controller;

import com.itcast.pojo.Books;
import com.itcast.service.BookService;
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.RequestMapping;

import java.util.ArrayList;
import java.util.List;

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

    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    @RequestMapping("/allBook")
    public String QueryAllBook(Model model){
     
        List<Books> booksList = bookService.queryAllBook();
        model.addAttribute("bookList",booksList);
        return "allBook";
    }

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

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

    @RequestMapping("/updateBookPage")
    public String updateBookPage(int id,Model model){
     
        Books book = bookService.queryBookByID(id);
        model.addAttribute("book",book);
        return "updateBookPage";
    }

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

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

    @RequestMapping("/queryBookByName")
    public String queryBookByName(String bookName,Model model){
     
        Books Qbooks = bookService.queryBooksByName(bookName);
        System.out.println("queryBookByName=="+Qbooks);
        List<Books> booksList = new ArrayList<>();
        booksList.add(Qbooks);

        if (Qbooks == null){
     
            booksList = bookService.queryAllBook();
        }
        model.addAttribute("bookList",booksList);
        return "allBook";
    }
}

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2020/9/8
  Time: 15:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>图书城title>
  head>
  <body>
 <h1>
   <a href="${pageContext.request.contextPath}/Book/allBook">进入书籍页面a>
 h1>
  body>
html>

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 clearfix">
         <div class="col-lg-12 column">
             <div class="page-header">
                 <h1>书籍列表——————显示所有书籍h1>
             div>
         div>
         <div class="row">
             <div class="col-md-4">
                 <a class="btn btn-primary" href="${pageContext.request.contextPath}/Book/addBookPage">添加书籍a>
                 <a class="btn btn-primary" href="${pageContext.request.contextPath}/Book/allBook">全部书籍a>
             div>

             <form action="${pageContext.request.contextPath}/Book/queryBookByName" method="post" class="form-inline" style="float: right">
                 <div class="form-group">
                     <input type="text" class="form-control" name="bookName" placeholder="输入查询的书名">
                 div>
                 <button type="submit" class="btn btn-primary">提交button>
             form>
         div>

     div>

     <div>
         <div class="row clearfix">
             <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="${bookList}">
                     <tr>
                         <td>${book.bookID}td>
                         <td>${book.bookName}td>
                         <td>${book.bookCounts}td>
                         <td>${book.detail}td>
                         <td>
                             <a href="${pageContext.request.contextPath}/Book/updateBookPage?id=${book.bookID}">修改a>
                              | 
                             <a href="${pageContext.request.contextPath}/Book/deleteBook?id=${book.bookID}">删除a>
                         td>
                     tr>

                 c:forEach>
                 tbody>
             table>
         div>
     div>

 div>

body>
html>

addBookPage.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2020/9/8
  Time: 20:58
  To change this template use File | Settings | File Templates.
--%>
<%@ 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 clearfix">
        <div class="col-lg-12 column">
            <div class="page-header">
                <h1>新增书籍h1>
            div>
        div>
    div>

    <form action="${pageContext.request.contextPath}/Book/addBook" method="post">
        <div class="form-group">
            <label for="BookName">书籍名称:label>
            <input type="text" name="bookName" class="form-control" id="BookName" placeholder="书籍名称" required>
        div>

        <div class="form-group">
            <label for="BookCounts">书籍数量:label>
            <input type="text" name="bookCounts" class="form-control" id="BookCounts" placeholder="书籍数量" req1>
        div>

        <div class="form-group">
            <label for="BookDetail">书籍详情:label>
            <input type="text" name="detail" class="form-control" id="BookDetail" placeholder="书籍详情" required>
        div>

        <div class="form-group">
            <input type="submit" class="form-control" value="添加">
        div>

    form>
div>
body>
html>

updateBookPage.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2020/9/8
  Time: 20:58
  To change this template use File | Settings | File Templates.
--%>
<%@ 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 clearfix">
        <div class="col-lg-12 column">
            <div class="page-header">
                <h1>修改书籍h1>
            div>
        div>
    div>

    <form action="${pageContext.request.contextPath}/Book/updateBook" method="post">
        <input type="hidden" name="bookID" value="${book.bookID}">
        <div class="form-group">
            <label for="BookName">书籍名称:label>
            <input type="text" name="bookName" class="form-control" id="BookName" value="${book.bookName}" required>
        div>

        <div class="form-group">
            <label for="BookCounts">书籍数量:label>
            <input type="text" name="bookCounts" class="form-control" id="BookCounts" value="${book.bookCounts}" req1>
        div>

        <div class="form-group">
            <label for="BookDetail">书籍详情:label>
            <input type="text" name="detail" class="form-control" id="BookDetail" value="${book.detail}" required>
        div>

        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="修改">
        div>

    form>
div>
body>
html>

你可能感兴趣的:(SpringMVC)