整合SSM小Demo(图书管理)

整合SSM小Demo(图书管理)

1、环境准备

  • IDEA
  • Tomcat 9.0.41
  • MySQL 8.0.22
  • Maven 3.6
  • spring,mybatis等

2、创建数据库

创建一个存放书籍的表

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 '描述',
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,'从进门到进牢');

3、项目基本框架的搭建

1、新建一个maven项目,并为其添加web支持
2、在核心配置文件 pom.xml 中导入你所需要的环境

<dependencies>

    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
    dependency>

    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>8.0.22version>
    dependency>

    
    <dependency>
        <groupId>com.mchangegroupId>
        <artifactId>c3p0artifactId>
        <version>0.9.5.2version>
    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.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.5.2version>
    dependency>
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatis-springartifactId>
        <version>2.0.6version>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>5.3.3version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>5.3.3version>
    dependency>

    
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <version>1.18.16version>
    dependency>
dependencies>
3、在核心配置文件中加入build配置以解决静态资源导出问题

<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>
4、建立项目的基本结构和配置

基本架构

  • dao层处理数据
  • service层调用dao层,组合dao
  • pojo实体类,属性名要和数据库中属性名一致
  • controller层去进行具体业务的操作

项目配置文件

  • mybatis-config.xml mybatis的核心配置文件



<configuration>
    
configuration>
  • applicationContext.xml spring的核心配置文件

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

4、分层次编写

Mybatis层

1.数据库核心配置文件 database.properties

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

注意!

这里如果是使用MySQL5版本的话,driver应为com.mysql.jdbc.Driver,且MySQL8版本需增加时区判定问题&serverTimezone=GMT,将时区定为Asia/Shanghai或GMT,UTC都可。

2.使用IDEA连接数据库,同样需要注意时区问题

3.编写MyBatis的核心配置文件 mybatis-config.xml



<configuration>

    
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    
    
    <typeAliases>
        <package name="com.hsy.pojo"/>
    typeAliases>

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

configuration>

4.编写数据库所对应的实体类pojo.Books

这里使用lombok插件(懒人专属)

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

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
     

    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
    
}

5.编写Dao层的 Mapper接口 BookMapper

import com.hsy.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;

public interface BookMapper {
     

    //增加一本书
    int addBook(Books books);

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

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

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

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

    //搜索框查询书籍
    Books queryBookByName(@Param("bookName") String bookName);

}

6.编写接口对应的配置文件,并在这里编写sql语句 BookMapper.xml




<mapper namespace="com.hsy.dao.BookMapper">

    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
        value (#{bookName},#{bookCounts},#{detail});
    insert>

    <delete id="deleteBookByID" parameterType="int">
        delete from ssmbuild.books where bookID=#{bookID};
    delete>

    <update id="updateBook" parameterType="Books">
        update ssmbuild.books
        set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
        where bookID=#{bookID};
    update>

    <select id="queryBookByID" resultType="Books">
        select * from ssmbuild.books where bookID=#{bookID}
    select>

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

    <select id="queryBookByName" resultType="Books">
        select * from ssmbuild.books where bookName=#{bookName}
    select>
    
mapper>

7.dao层编写完毕后,这时需要编写service层的接口和实现类,以调用dao层

BookService接口

import com.hsy.pojo.Books;
import java.util.List;

public interface BookService {
     

    //增加一本书
    int addBook(Books books);

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

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

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

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

    //搜索框查询书籍
    Books queryBookByName(String bookName);
    
}

BookServiceImpl实现类

import com.hsy.dao.BookMapper;
import com.hsy.pojo.Books;
import java.util.List;

public class BookServiceImpl implements BookService{
     
    
    //service层调dao层:组合dao
    private BookMapper bookMapper;

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

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

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

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

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

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

    public Books queryBookByName(String bookName) {
     
        return bookMapper.queryBookByName(bookName);
    }
    
}

到这里mybatis层就编写完毕了。

spring层

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

2.编写spring整合dao层的配置文件 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
        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:property-placeholder location="classpath:database.properties"/>

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

        
        <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.hsy.dao"/>
    bean>
    
beans>

3.spring整合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"
       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:component-scan base-package="com.hsy.service"/>

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

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

    

beans>

到这里spring层就编写完毕了

springMVC层

1.配置web依赖 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>encodingFilterfilter-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>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

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

2.配置springMVC的核心配置文件 spring-mvc.xml


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

    
    <mvc:annotation-driven/>

    
    <mvc:default-servlet-handler/>

    
    <context:component-scan base-package="com.hsy.controller"/>

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

beans>

3.将spring所有的配置文件整合到spring核心配置文件中 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
        http://www.springframework.org/schema/beans/spring-beans.xsd">

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

beans>

配置文件就到这里,还剩下controller中具体操作的代码以及前端界面还没有写。

controller层及前端界面

1.controller方法一:查询全部书籍

@Controller
@RequestMapping("/book")
public class BookController {
     
    //controller层调用service层
    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookservice;

    //查询全部书籍,并返回到一个书籍展示界面
    @RequestMapping("/allBooks")
    public String list(Model model){
     
        List<Books> books = bookservice.queryAllBooks();
        model.addAttribute("list",books);
        return "allBooks";
    }

2.首页 index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

  
    首页
    
  
  
  

进入书籍界面

效果如下:

整合SSM小Demo(图书管理)_第1张图片

3.然后是书籍列表的界面 allBooks.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    书籍展示页面
    <%--BootStrap美化页面--%>
    



<%--从数据库中把书查询出来通过list遍历: C:foreach--%>
书籍编号 书籍名称 书籍数量 书籍详情 操作
${book.bookID} ${book.bookName} ${book.bookCounts} ${book.detail} 修改   |   删除

效果如下:

整合SSM小Demo(图书管理)_第2张图片

4.controller方法二:添加书籍

//跳转到增加书籍的页面
    @RequestMapping("/toAddBook")
    public String toAddBook(){
     
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("/addBook")
    public String addBook(Books books){
     
        bookservice.addBook(books);
        return "redirect:/book/allBooks";//重定向到@RequestMapping("/allBooks")请求
    }

5.添加书籍的界面 addBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    新增书籍
    <%--BootStrap美化页面--%>
    



效果如下:

整合SSM小Demo(图书管理)_第3张图片

6.controller方法三:修改(更新)书籍

//跳转到修改书籍的界面
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(int id,Model model){
     
        Books books = bookservice.queryBookByID(id);
        model.addAttribute("queryBook",books);
        return "updateBook";
    }

    //修改书籍的请求
    @RequestMapping("/updateBook")//这里使用传统风格传参
    public String updateBook(Books books){
     
        bookservice.updateBook(books);
        return "redirect:/book/allBooks";
    }

7.修改书籍的界面 updateBook.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    修改书籍
    <%--BootStrap美化页面--%>
    



<%--前端传递bookID隐藏域--%>

效果如下:

在这里插入图片描述

8.controller方法四:删除书籍

//删除书籍的请求
    @RequestMapping("/deleteBook/{bookID}")//这里使用Restful风格传参
    public String deleteBook(@PathVariable("bookID") int id){
     
        bookservice.deleteBookByID(id);
        return "redirect:/book/allBooks";
    }

5、实现搜索框依据书名查询书籍功能

1.首先我们需要在前端展示所有书籍的界面添加一个搜索框和查询按钮

${error}

2.先写底层代码,在mapper中添加一个接口

//搜索框查询书籍
    Books queryBookByName(@Param("bookName") String bookName);

3.接口写完了,我们需要在配置文件里把sql语句补上

<select id="queryBookByName" resultType="Books">
    select * from ssmbuild.books where bookName=#{bookName}
select>

4.dao层写完了,这时我们去写service层

//搜索框查询书籍
    Books queryBookByName(String bookName);

5.然后写service的实现类

public Books queryBookByName(String bookName) {
     
        return bookMapper.queryBookByName(bookName);
    }

6.最后我们去写controller层的具体操作

//查询书籍的请求
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
     
    Books books = bookservice.queryBookByName(queryBookName);
    List<Books> list =new ArrayList<Books>();
    list.add(books);

    if (books==null){
     
        list=bookservice.queryAllBooks();
        model.addAttribute("error","未查到您想查询的书籍");
    }

    model.addAttribute("list",list);
    return "allBooks";
}

到这里这个web小demo就算完成了~

这时候我们可以配置tomcat然后运行项目就可以啦!

6、写在后面

第一个SSM整合案例,完成了增删改查的基本操作,这是一个非常底层,基础的项目,我们可以在这个项目的基础上完善自己的知识面,增加扩展更多的功能,使其成为一个非常强大的网站。其实学到这里才算真正入了后台开发的门,后面还有很长的路要走。作为一个刚转专业到计算机的大二小白,我深切的感受到了计算机的强大,同时也在不停地激励自己努力变强。这个demo虽然非常的简单,功能也不全面,但却是认认真真敲下来的,在这里要感谢“狂神说JAVA”,课讲得非常nice~学到了很多,接下来就是多花些时间,争取不看任何资料熟练地把这个项目完整地给敲出来,相信会有非常大的收获。

这是我的第一篇博客,希望大家不喜勿喷叭,多多支持~其实平常也记了很多的笔记,就是太懒了想不起来发出来(手动狗头)

你可能感兴趣的:(SSM,java)