整合SSM(以书城项目为例)

整合SSM(以书城项目为例)

0.项目介绍

功能介绍:

​ 实现书城书籍的增删改查功能(孱弱的功能。。)

用到的知识:

​ MySQL数据库,Spring,JavaWeb及MyBatis知识

​ 以及简单的前端知识;

1.准备工作

1)数据库

建表语句
CREATE TABLE `books`(
	`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书籍编号',
	`bookName` VARCHAR(100) NOT NULL COMMENT '书籍名称',
	`bookCounts` INT(10) NOT NULL COMMENT '书籍数量',
	`details` VARCHAR(100) NOT NULL COMMENT '备注',
	KEY `bookID` (`bookID`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
添加初始数据
INSERT INTO `books` VALUES
(1,'从入门到放弃',1,'Java'),
(2,'从删库到跑路',5,'MySQL'),
(3,'从进门到进牢',10,'Linux');

2)创建项目

配置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>com.xqcgroupId>
    <artifactId>BookStoreartifactId>
    <version>1.0-SNAPSHOTversion>

    <dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        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.2version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.1.9.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.1.9.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.18version>
        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>

3)框架搭建

创建需要的包以便于管理:

​ ①pojo:存放封装数据的实体类,一般来说与数据库对应

​ ②dao:存放操作数据库的接口,以及对应的Mapper配置文件

​ ③service:业务层,存放服务接口以及对应的实现类

​ ④controller:控制层,存放实现与前端页面的请求回应的类

必要的配置文件:

​ applicationContext.xml (Spring的配置文件,之后会在这里导入其他框架的配置文件交给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>

​ mybatis-config.xml(mybatis的配置文件)



<configuration>

    
    <settings>
        
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    
    <typeAliases>
        
        <package name="com.xqc.pojo"/>
    typeAliases>
    
    <mappers>
        
        <package name="com.xqc.dao"/>
    mappers>
configuration>

4)idea链接数据库

便于之后代码的编写:
整合SSM(以书城项目为例)_第1张图片
可能的设置:时区设置
整合SSM(以书城项目为例)_第2张图片

2.整合过程

实体类

① com.xqc.pojo.Books(对照数据库中的字段编写)

package com.xqc.pojo;

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 details;
}

dao层

① com.xqc.dao.BooksMapper(增删改查的接口)

package com.xqc.dao;

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

import java.util.List;

public interface BooksMapper {
     
    int addBooks(Books books);
    int deleteBooks(@Param("bookID") int id);
    int updateBooks(Books books);
    Books queryBooksById(@Param("bookID") int id);
    List<Books> queryAllBooks();
}

② com.xqc.dao.BooksMapper.xml(对应接口的具体sql语句)



<mapper namespace="com.xqc.dao.BooksMapper">
    <insert id="addBooks" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, details)
        values
        (#{bookName}, #{bookCounts}, #{details});
    insert>

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

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

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

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

③ database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localh![在这里插入图片描述](https://img-blog.csdnimg.cn/20210206024915983.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3h2Y2Fpbg==,size_16,color_FFFFFF,t_70)
ost:3306/ssmbuild?useSSL=true&useUnicode=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123568

④ 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.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />
        <property name="maxActive" value="20" />

        
        <property name="maxWait" value="60000" />

        
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

        
        <property name="filters" value="stat" />
    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.xqc.dao"/>
    bean>
beans>

service层

① com.xqc.service.BooksService(服务接口,这里太懒了直接直接使用dao层的增删改查功能)

package com.xqc.service;

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

import java.util.List;

public interface BooksService {
     
    int addBooks(Books books);
    int deleteBooks(int id);
    int updateBooks(Books books);
    Books queryBooksById(int id);
    List<Books> queryAllBooks();
}

② com.xqc.service.Impl.BooksServiceImpl(服务接口的实现类)

package com.xqc.service.Impl;

import com.xqc.dao.BooksMapper;
import com.xqc.pojo.Books;
import com.xqc.service.BooksService;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class BooksServiceImpl implements BooksService {
     
    BooksMapper mapper;

    public void setMapper(BooksMapper mapper) {
     
        this.mapper = mapper;
    }

    @Override
    public int addBooks(Books books) {
     
        return mapper.addBooks(books);
    }

    @Override
    public int deleteBooks(int id) {
     
        return mapper.deleteBooks(id);
    }

    @Override
    public int updateBooks(Books books) {
     
        return mapper.updateBooks(books);
    }

    @Override
    public Books queryBooksById(int id) {
     
        return mapper.queryBooksById(id);
    }

    @Override
    public List<Books> queryAllBooks() {
     
        return mapper.queryAllBooks();
    }
}

③ spring-service.xml(扫描@Component注解,实现自动注入)


<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.xqc.service" />
    <bean id="BooksServiceImpl" class="com.xqc.service.Impl.BooksServiceImpl">
        <property name="mapper" ref="booksMapper"/>
    bean>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
beans>

controller层

① com.xqc.conrtroller.BooksController(接受请求并返回页面跳转信息)

package com.xqc.controller;

import com.xqc.service.BooksService;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/books")
public class BooksController {
     
    @Autowired
    @Qualifier("BooksServiceImpl")
    private BooksService booksService;

    @GetMapping("/all")
    public String getAllBooks(Model model){
     
        model.addAttribute("BooksList", booksService.queryAllBooks());
        return "all";
    }
}

② spring-mvc.xml(配置controller信息)


<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">
    
    
    <mvc:annotation-driven />
    
    <mvc:default-servlet-handler/>

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

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

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

3.增加Web框架

1)必要的步骤

整合SSM(以书城项目为例)_第3张图片

2)web.xml

​ 配置web服务器,核心件:DispatcherServlet


<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>DispatcherServletservlet-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>DispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        filter-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>

3) 渲染数据(学艺不精,直接偷过来了)

​ index.jsp

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



  首页
  



点击进入列表页

​ all.jsp

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


    书籍列表
    
    
    



书籍编号 书籍名字 书籍数量 书籍详情 操作
${book.getBookID()} ${book.getBookName()} ${book.getBookCounts()} ${book.getDetails()} 更改 | 删除

4)记得打包!!

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