其他分享
首页 > 其他分享> > 简单SSM整合

简单SSM整合

作者:互联网

准备工作

1、新建一个Maven web工程,导入相关的依赖
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</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>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</version>
        </dependency>
        <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.6</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.7</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.19</version>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
    </dependencies>

2、建立项目需要的包,项目的整体结构为:

SSM整合:Dao层

1、数据库建表

CREATE DATABASE ssmbuild;

USE ssmbuild;

CREATE table books(
bookID INT(10) not null 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,'从入门到精通');

2、在pojo包新建数据库实体类Books

package com.chen.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 detail;
}

3、dao层编写实体类接口BookMapper

package com.chen.dao;
import com.chen.pojo.Books;
import java.util.List;

public interface BookMapper {
    int addBook(Books books);
    int deleteBookById(int id);
    int updateBook(Books books);
    Books queryBookById(int id);
    List<Books> queryAllBook();
}

4、根据BookMapper接口,编写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.chen.dao.BookMapper">
    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
        values (#{bookName},#{bookCounts},#{detail})
    </insert>

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

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

    <select id="queryBookById" parameterType="int" resultType="Books">
        select * from ssmbuild.books
        where bookID=#{id}
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from ssmbuild.books
    </select>
</mapper>

5、配置数据库源
注意:MySQL版本大于8的话需要设置时区,不然会报错

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

6、编写mybatis-config.xml配置文件

<?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>
    <!--配置数据源,由Spring完成-->
    <typeAliases>
        <!--自动给这个包下的类起别名-->
        <package name="com.chen.pojo"/>
    </typeAliases>
</configuration>

7、编写spring-dao.xml配置文件,将Dao层的类交给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
         http://www.springframework.org/schema/context/spring-context.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}"/>
    </bean>

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

    <!--4、配置dao层接口扫描包,动态的实现dao层接口可以注入到Spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.chen.dao"/>
    </bean>

</beans>

SSM整合:Service层

Service层叫服务层,被称为服务,粗略的理解就是对一个或多个DAO进行的再次封装,封装成一个服务,但本文只是简单整合,所以Service层实现的功能和Dao层差不多。
1、在service包下新建BookService接口

package com.chen.service;
import com.chen.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> queryAllBook();
}

2、编写BookService接口的实现类BookServiceImpl

package com.chen.service;
import com.chen.dao.BookMapper;
import com.chen.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService{
    private BookMapper mapper;

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

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

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

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

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

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

3、将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
         http://www.springframework.org/schema/context/spring-context.xsd">

    <!--1、扫描service下的包-->
    <context:component-scan base-package="com.chen.service"/>

    <!--2、将所有的业务类注入到spring中,可以直接配置,也可以通过注解-->
    <!--用注解的话,直接指定注解扫描的包:<context:component-scan base-package="com.chen.service"/>-->
    <bean id="bookServiceImpl" class="com.chen.service.BookServiceImpl">
        <property name="mapper" ref="bookMapper"/>
    </bean>

    <!--3、声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

SSM整合:Controller层

1、controller包下建立BookController类

package com.chen.controller;
import com.chen.pojo.Books;
import com.chen.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.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;

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

2、在WEB-INF目录下新建jsp目录,在jsp目录下新建allBook.jsp文件作为BookController类中allBook方法的跳转页面。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h3>书籍展示</h3>
</body>
</html>

3、编写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: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
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--1、注解驱动-->
    <mvc:annotation-driven/>

    <!--2、静态资源过滤-->
    <mvc:default-servlet-handler/>

    <!--3、自动扫描包-->
    <context:component-scan base-package="com.chen.controller"/>

    <!--4、试图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

4、最后配置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">

    <!--1、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>

    <!--2、乱码解决-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--3、Session-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

标签:int,SSM,books,整合,简单,import,Books,com,public
来源: https://www.cnblogs.com/lchen-java/p/16293697.html