【ssm个人博客项目实战01】SSM环境搭建1、ssm系统架构2、项目整合

2018-08-21 10:19:04 浏览数 (1)

前言

代码语言:javascript复制
今天开始就做一个个人博客实战项目了,首先就项目环境的搭建,万丈高楼平地起。这篇 博客主要讲解基于maven的ssm项目整合。

1、ssm系统架构

这里写图片描述

整合步骤

第一步:

MyBatis和Spring整合,通过Spring管理mapper接口。

使用mapper的扫描器自动扫描mapper接口在Spring中进行注册。

第二步:

通过Spring管理Service接口。

使用配置方式将Service接口配置在Spring配置文件中。

实现事务控制。

第三步:

由于SpringMVC是Spring的模块,无需整合这两个。

项目架构:

这里写图片描述

下面讲解部分包/文件作用

mapper:存放mybatis的mapper文件夹 log4j.properties:log4j日志属性文件 mybatis-conf.xml:mybatis全局配置文件 spring-bean.xml:spring与mybatis整合配置文件 spring-mvc.xml:spring mvc配置文件

下面就开始我们的项目整合吧

2、项目整合

2.1、新建maven项目 添加依赖

maven是一个优秀的项目对象管理器工具 我可以通过在pom.xml中添加需要的jar包的依赖就可以导入对应的jar包了,非常的方便。 下面就列出整合ssm所对应的依赖

代码语言:javascript复制
<!-- 添加sevlet支持 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <!-- 添加jsp支持 -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
    </dependency>
    <!-- 添加jstl支持 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- 添加spring支持 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <!--spring test支持-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <!--spring mvc支持-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <!--spring 事务管理支持-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <!--spring jdbc操作支持-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <!--spring aop编程支持-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.0.RELEASE</version>
    </dependency>

    <!-- 添加mybatis支持 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <!--  jdbc驱动包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>

    <!-- 添加阿里巴巴连接池Druid支持 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.16</version>
    </dependency>

    <!-- 添加log4j日志 -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.21</version>
    </dependency>
    <!-- apache共公包 -->
     <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- 添加junit支持 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

2.2spring与mybatis整合

2.2.1 新建mybatis-conf.xml文件

这个文件主要配置mybatis全局配置文件 例如 别名 驼峰命名自动转换等 在这里我暂时只配置别名

代码语言:javascript复制
<?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="ssm.blog.entity"/>
    </typeAliases>
</configuration>

2.2.2新建spring-beans.xml文件

整合主要步骤

  • 开启包扫描
  • 配置druid数据源
  • 列表内容
  • 配置sqlSessionFactory
  • 开启mybatis dao接口扫描

具体配置注解讲的很清楚

代码语言:javascript复制
<?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">
    <!-- 开启包扫描-->
    <context:component-scan base-package="ssm.blog"/>
    <!-- 配置druid数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db_blog"/>
    </bean>
    <!-- 配置mybatis的sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描mapper.xml文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <!-- 载入mybatis全局配置文件-->
        <property name="configLocation" value="classpath:mybatis-conf.xml"/>
    </bean>

    <!-- 配置mybatis dao接口扫描-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="ssm.blog.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>
<!-- 配置spring的声明式事务,名字为默认值 -->  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
      
    <!-- 开启事务控制的注解支持 -->  
    <tx:annotation-driven transaction-manager="transactionManager"/>、、

现在mybatis与spring整合已经算完成了 接下来我们测试一下

2.2.3测试spring与mybatis整合

1、表结构

这里写图片描述

sql 文件

代码语言:javascript复制
DROP DATABASE IF EXISTS db_blog;
/*创建数据库,并设置编码*/
CREATE DATABASE db_blog DEFAULT CHARACTER SET utf8;

USE db_blog;

CREATE TABLE `t_blogger` (
  `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '博主id',
  `username` VARCHAR(50) NOT NULL COMMENT '博主姓名',
  `password` VARCHAR(100) NOT NULL COMMENT '博主密码',
  `profile` TEXT COMMENT '博主信息',
  `nickname` VARCHAR(50) DEFAULT NULL COMMENT '博主昵称',
  `sign` VARCHAR(100) DEFAULT NULL COMMENT '博主签名',
  `imagename` VARCHAR(100) DEFAULT NULL COMMENT '博主头像路径',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

2、实体类

代码语言:javascript复制
package ssm.blog.entity;

import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * Created by xp on 2017/4/13.
 * @author xp
 * @Description 博主信息实体类
 */
@Component  //注册bean 为spring容器管理
public class Blogger implements Serializable {

    private Integer id;
    private String userName;    //用户名
    private String password;    //密码
    private String profile;     //博主信息
    private String nickName;    //昵称
    private String sign;        //博主签名
    private String imageName;   //图片路径

    public Blogger(String userName, String password, String profile, String nickName, String sign, String imageName) {
        this.userName = userName;
        this.password = password;
        this.profile = profile;
        this.nickName = nickName;
        this.sign = sign;
        this.imageName = imageName;
    }

    public Blogger() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getProfile() {
        return profile;
    }

    public void setProfile(String profile) {
        this.profile = profile;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    @Override
    public String toString() {
        return "Blogger{"  
                "id="   id  
                ", userName='"   userName   '''  
                ", password='"   password   '''  
                ", profile='"   profile   '''  
                ", nickName='"   nickName   '''  
                ", sign='"   sign   '''  
                ", imageName='"   imageName   '''  
                '}';
    }
}

3、dao接口以及mapper文件 dao接口

代码语言:javascript复制
package ssm.blog.dao;

import org.springframework.stereotype.Repository;
import ssm.blog.entity.Blogger;

/**
 * Created by xp on 2017/4/13.
 * 博主dao接口
 */
@Repository //注册为持久层的bean
public interface BloggerDao {
    /**
     * 查询博主信息
     * @return
     */
    Blogger getBloggerData();
}

mapper

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="ssm.blog.dao.BloggerDao">
    <!--
        返回结果映射
        如果开启驼峰命名转换且命名规范该段代码可以不写
        因为配置别名 所以type属性使用的是mybatis-conf中的别名
        -->
    <resultMap type="Blogger" id="BloggerResult">
        <id property="id" column="id"/>
        <result property="userName" column="username"/>
        <result property="password" column="password"/>
        <result property="profile" column="profile"/>
        <result property="nickName" column="nickname"/>
        <result property="sign" column="sign"/>
        <result property="imageName" column="imagename"/>
    </resultMap>
    <!--  定义字段集合 -->
    <sql id="BloggerColumns">
        id,username,password,profile,nickname,sign,imagename
    </sql>
    <!-- 接口中getBloggerData 具体实现-->
    <select id="getBloggerData" resultMap="BloggerResult">
            select <include refid="BloggerColumns"/>    from t_blogger where id = 1
    </select>
</mapper>

4、log4j.properties 文件 创建log4j.properties 打印日志 查看执行sql语句

代码语言:javascript复制
log4j.rootLogger=DEBUG, Console  
  
#Console  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  
  
log4j.logger.java.sql.ResultSet=INFO  
log4j.logger.org.apache=INFO  
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG  

5、创建测试类并测试 BloggerDaoTest

代码语言:javascript复制
package ssm.blog.dao;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import ssm.blog.entity.Blogger;

import javax.annotation.Resource;

import static org.junit.Assert.*;

/**
 * Created by xp on 2017/4/13.
 */
@RunWith(SpringJUnit4ClassRunner.class) //使用spring测试
@ContextConfiguration(locations = "classpath:spring-beans.xml") //设置spring配置文件路径
public class BloggerDaoTest {

    @Resource   //注入BloggerDao对象
    private BloggerDao bloggerDao;

    @Test
    public void getBloggerData() throws Exception {
        Blogger blogger = bloggerDao.getBloggerData();
        System.out.println(blogger);
    }

}

打印结果

这里写图片描述

成功打印结果 说明spring与mybatis整合成功。

2.3spring与springmvc整合

2.3.1创建spring-mvc.xml

代码语言:javascript复制
<?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">

    <!-- 扫描所有ssm.blog.controller包下面的所有controller -->
    <context:component-scan base-package="ssm.blog.controller"/>
    <!-- 开启注解配置-->
    <mvc:annotation-driven/>
    <!-- 静态资源解析,包括js,css,img... -->
    <mvc:resources location="/static/" mapping="/static/**"/>
    <!-- 配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--视图前缀-->
        <property name="prefix" value="/"/>
        <!--视图后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

2.3.2 配置web.xml文件

注释讲的很清楚 我就不再讲了

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

    <!--spring配置文件路径-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-beans.xml</param-value>
    </context-param>
    <!-- 配置spring监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--spring mvc核心servlet-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 初始化参数配置 springnvc配置文件路径-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <async-supported>true</async-supported>
        <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>
</web-app>

2.3.2测试

新建BloggerController

代码语言:javascript复制
package ssm.blog.controller;

import jdk.internal.org.objectweb.asm.tree.analysis.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by xp on 2017/4/13.
 * 博主控制器
 */
@Controller  //注册为控制器bean
@RequestMapping(value = "/blog")    //请求路径
public class BloggerController {

    @ResponseBody  //返回json数据
    @RequestMapping(value="/hello")
    public String hello(){
        return "hello";
    }

}

发布项目到tomcat 打开浏览器输入:http://localhost:8080/blog/hello 结果:

这里写图片描述

至此我们ssm三大框架已经整合完毕,接下来就是个人博客实战开发了

0 人点赞