Java之SpringMVC-SSM整合

Posted CoLoo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java之SpringMVC-SSM整合相关的知识,希望对你有一定的参考价值。

SSM整合

sql

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

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

pom.xml

    <dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</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</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.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

spring-dao.xml ==> Spring整合Dao

<?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:property-placeholder location="classpath:database.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}"/>

        <!-- c3p0连接池的私有属性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2"/>
    </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">
<!--        注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--        要扫描的dao包-->
        <property name="basePackage" value="com.zh1z3ven.dao"/>
    </bean>
</beans>

database.properties,连接数据库所需静态资源文件

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

mybatis-config.xml , mybatis配置文件

<?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>
  <!-- 设置别名 -->
    <typeAliases>
        <package name="com.zh1z3ven.pojo"/>
    </typeAliases>
  <!-- 注册Mapper.xml -->
    <mappers>
        <mapper resource="com/zh1z3ven/dao/BookMapper.xml"/>
    </mappers>

</configuration>

spring-service.xml ==> spring整合service

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

<!--   扫描service包-->
    <context:component-scan base-package="com.zh1z3ven.service"/>
<!--    将service类注入到Spring 通过配置或注解实现-->
    <bean id="BookServiceImpl" class="com.zh1z3ven.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-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
       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/>
<!--    扫描controller包-->
    <context:component-scan base-package="com.zh1z3ven.controller"/>
<!--    视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

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

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

<!--    配置SpringMVC中DispachFactory-->
    <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>

<!--    乱码过滤-->
    <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>

<!--    Session Config过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

整体项目结构大致如下,之后只需要丰富Dao中的接口,主要是添加CRUD功能即可,然后在Mapper.xml中编写SQL语句;在Service层中调用Dao层完成基础CRUD操作,且也可以配置一些其他操作,如事务处理等;之后在Controller层调用和处理Service逻辑并将需要的内容保存在Model上下文中供前端页面获取并渲染呈现给用户。

简单示例:

pojo

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;

}

Dao层

BookMapper.java

public interface BookMapper {
    //add
    int addBook(Book book);

    //delete	这里@Param("bookID")中的值与mybatis中sql语句的#{bookID}名称一致才可以获取到
    int deleteBookById(@Param("bookID") int id);

    //update
    int updateBook(Book book);

    //select by id
    Book queryBookById(@Param("bookID") int id);

    //select all
    List<Book> queryAllBook();

}

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对应一个接口-->
<mapper namespace="com.zh1z3ven.dao.BookMapper">

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

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

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

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

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

Service层

BookService.java

public interface BookService {

    //add
    int addBook(Book book);

    //delete
    int deleteBookById(int id);

    //update
    int updateBook(Book book);

    //select by id
    Book queryBookById(int id);

    //select all
    List<Book> queryAllBook();


}

BookServiceImpl.java

//dao和service就是mvc中的model层
public class BookServiceImpl implements BookService{
    //Service层调Dao层
    //调Dao,创建set,方便spring整合
    private BookMapper bookMapper;

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

    //通过调用dao层示例对象去操作数据库,同时还可以在service层做一些其他的操作,如事务的操作
    public int addBook(Book book) {
        return bookMapper.addBook(book);
    }

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

    public int updateBook(Book book) {
        return bookMapper.updateBook(book);
    }

    public Book queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    public List<Book> queryAllBook() {
        return bookMapper.queryAllBook();
    }
}

Controller层

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

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

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

之后在/WEB-INF/jsp/allBook.jsp中使用${list}即可在spring上下文中获取到list这个属性值并渲染到前端页面。

结语:

SSM整合其实基本都是各种xml配置文件将三层架构串起来,多看几遍手动跟下配置其实就能捋清MVC的整体架构了。
PS:想起了之前在学校的日子,那会其实也蛮想学Java,包括我自己第一本关于编程的书就是Java的,但是又听在学的同学说很难,我也就觉得Java好难然后搁置了。其实这次跟着学下来感觉还不错,没想象中的那么难,Java的逻辑很清晰。道阻且长,行则将至。

所有内容仅限于维护网络安全学习参考

以上是关于Java之SpringMVC-SSM整合的主要内容,如果未能解决你的问题,请参考以下文章

Java之SSM框架整合-案例IDEA版(一篇文章精通系列)Spring+SpringMVC+MyBatis(整合源代码)

JAVA之AOP

Java语言基础之方法的设计

springboot Thymeleaf 整合

全栈编程系列SpringBoot整合Shiro(含KickoutSessionControlFilter并发在线人数控制以及不生效问题配置启动异常No SecurityManager...)(代码片段

Java开发Spring之IOC详解第二篇(注解开发JdbcTemplatem模板Junit整合)