【SSM框架从零开始4】IntelliJ IDEA搭建SSM框架

代码地址:https://pan.baidu.com/s/18dyR6GDcsbsF5CDd3tJ85g 密码:q7je

SSM:spring + spring mvc + mybatis
可以先看看我之前写的spring mvc怎么搭以及怎么使用Mybatis-Generator自动生成Dao、Model层相关代码,再看这篇,传送门:
IntelliJ IDEA搭建最简单的Spring MVC项目
IntelliJ IDEA下Spring MVC数据库配置与增删改查开发
使用Mybatis-Generator自动生成Dao、Model层相关代码
与之相关的就不再写了。

1 新建工程,并完善目录结构与前面两篇文章一样

目录结构.png

目录结构多了个service,用以放业务逻辑。

2 添加依赖包

pom.xml中依赖包加入:

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.7</maven.compiler.source>
  <maven.compiler.target>1.7</maven.compiler.target>
  <!-- spring版本号 -->
  <spring.version>5.0.5.RELEASE</spring.version>
</properties>   
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>   
  <!-- 数据库 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.37</version>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <!--jdbc连接池-->
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
  </dependency>   
  <!-- DAO: MyBatis -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.3.0</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.3</version>
  </dependency>   
  <!-- Servlet web -->
  <dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
  </dependency>
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>   
  <!--Gson-->
  <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
  </dependency>   
  <!-- Spring -->
  <!-- Spring核⼼ -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <!-- Spring DAO层 -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <!-- Spring web -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <!-- Spring test -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
</dependencies>

3 添加各种配置文件

数据源

在resources下面新建jdbc.properties文件。
这个文件用以配置jdbc数据源以及数据连接池的各种参数,单独放到文件便于修改。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/cmtable?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
#最大连接数
maxPoolSize=20
#最小连接数
minPoolSize=10
#连接超时时间
checkoutTimeout=60000
#失败重连次数
acquireRetryAttempts=3

mybatis-config.xml

在resources下面新建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>
    <!--配置全局属性-->
    <settings>
        <!-- 使⽤jdbc的getGeneratedKeys获取数据库⾃增主键值 -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 使⽤列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>

这个作为MyBatis的全局配置文件,还有很多参数可以设置,这里不细讲。

扫描 sql 配置⽂件:mapper 需要的 xml ⽂件

在resources文件夹下面新建mapper目录,用以放置那些对应的xml文件。

applicationContext.xml Spring全局配置文件

在resources下面新建applicationContext.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"
       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/tx http://www.springframework.org/schema/tx/springtx.xsd">

    <!--配合MyBatis-->
    <!--配置数据库参数-->
    <context:property-placeholder location="classpath:jdbc.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}"/>
        <!--c3p0连接池私有属性-->
        <property name="maxPoolSize" value="${maxPoolSize}"/>
        <property name="minPoolSize" value="${minPoolSize}"/>
        <property name="autoCommitOnClose" value="false"/>
        <property name="checkoutTimeout" value="${checkoutTimeout}"/>
        <property name="acquireRetryAttempts" value="${acquireRetryAttempts}"/>
    </bean>

    <!-- 配置 SqlSessionFactory 对象,spring和MyBatis完美整合,不需要mybatis的配置映射文件-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置 MyBaties 全局配置⽂件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 扫描 model 包 使⽤别名 -->
        <property name="typeAliasesPackage" value="com.cm.model"/>
        <!-- 扫描 sql 配置⽂件:mapper 需要的 xml ⽂件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!-- 配置扫描 dao 接⼝包, 动态实现 dao 接⼝, 注⼊到 Spring 容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注⼊ sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描 dao 接⼝包 -->
        <property name="basePackage" value="com.cm.dao"/>
    </bean>
    <!--spring-service-->
    <!-- 扫描 service 包下所有使⽤注解的类型 -->
    <context:component-scan base-package="com.cm.service"/>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注⼊数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

mvc-dispatcher.xml

在resources下面新建mvc-dispatcher.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:p="http://www.springframework.org/schema/p"
       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/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- controller扫描器 -->
    <context:component-scan base-package="com.cm.controller"/>


    <!-- 配置注解驱动 -->
    <mvc:annotation-driven/>
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/views/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--静态资源默认servlet配置
        (1)加⼊对静态资源的处理: js,gif,png
        (2)允许使⽤"/"做整体映射
    -->
    <mvc:default-servlet-handler/>
</beans>

web.xml

与前面文章一模一样。

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--Spring MVC 配置 并添加监听-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!-- 字符过滤器 传值乱码-->
  <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>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--配置前端控制器 进行请求分发 DispatcherServlet本质也是一个Servlet -->
  <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:mvc-dispatcher.xml</param-value>
    </init-param>
    <!--标记容器启动的时候就启动这个servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <!--拦截所有-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

好了,所有的配置文件都弄完了!

4 开发

建表。

MySQL表.png

使用之前文章里面说的方法自动生成Model和Dao以及对应的xml代码。

看看生成的代码,UserModel.java与前面类似,跳过。

其他的只是能参考,在这个基础上改,毕竟生成的有的接口不符合我们的想法。

    package com.cm.dao;
    
    import com.cm.model.UserModel;
    import java.util.List;
    public interface UserDao {
        List<UserModel> getAllUsers();
        UserModel getUser(String id);
        boolean addUser(UserModel userModel);
        boolean updateUser(String id, String name);
        boolean deleteUser(String id);
    }

MyBatis有个好处就是我们不用自己写实现,只需要配置对应的xml为其提供sql语句就行,在resources下的mapper文件夹下面新建UserDao.xml。模仿我们生成的xml进行修改。

    <?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="com.cm.dao.UserDao">
        <select id="getAllUsers" resultType="UserModel">
            select * from user
        </select>
        
        <select id="getUser" resultType="UserModel">
            select * from user where id = #{id}
        </select>
    
        <insert id="addUser">
            <!--ignore忽略自动增长的主键id-->
            insert ignore into user (name, age) values (#{id}, #{name})
        </insert>
        
        <update id="updateUser">
            update user set name=#{name} where id=#{id}
        </update>
    
        <delete id="deleteUser" parameterType="String">
            delete from user where id=#{id}
        </delete>
    </mapper>

其实就是一堆sql语句,namespace表示对应的类。id对应方法名,#{name}表示传入的参数。parameterType为入参类型,可以省略。

service层

在service中新建UserService,放置业务逻辑代码。可以这么理解,Dao颗粒度比较小,基本操作,但是service颗粒度比较大,放业务逻辑操作。

    package com.cm.service;
    
    import com.cm.dao.UserDao;
    import com.cm.model.UserModel;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import java.util.List;
    
    @Service
    @Transactional
    public class UserService {
        @Autowired
        private UserDao userDao;
    
        public List<UserModel> getAllUsers(){
            return userDao.getAllUsers();
        }
    
        public UserModel getUser(String id) {
            return userDao.getUser(id);
        }
        
        boolean addUser(UserModel userModel) {
            return userDao.addUser(userModel);
        }
        
        boolean updateUser(String id, String name) {
            return userDao.updateUser(id, name);
        }
        
        boolean deleteUser(String id) {
            return userDao.deleteUser(id);
        }
    }

学习阶段就不写太大的业务逻辑了。
说几个:
(1) @Service 标记为service,这样就能被Spring扫描到。
(2)@Transactional,我们前面配置文件开启了事务处理。业务逻辑需要进行事务处理。
标注在类前:标示类中所有方法都进行事务处理
标注在接口、实现类的方法前:标示方法进行事务处理
(3)@Autowired这个前面文章讲过了,自动注入。

Controller 层

在controller下面新建UserController.java。内容就不全写了,以两个为例。其他类似。

    package com.cm.controller;
    
    import com.cm.model.UserModel;
    import com.cm.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.List;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
        private UserService userService;
        @Autowired
        public UserController(UserService userService) {
            this.userService = userService;
        }
    
        @RequestMapping(value="getAllUsers",method = RequestMethod.GET)
        @ResponseBody
        public List<UserModel> getAllUsers() {
            List<UserModel> userModels = userService.getAllUsers();
            return userModels;
        }
    
        @RequestMapping(value="getUser",method = RequestMethod.GET)
        @ResponseBody
        public UserModel getUser(String id) {
            UserModel userModel = userService.getUser(id);
            return userModel;
        }
    }

5 测试

配置Tomcat,方法前面说过了。表中插入一些数据。用浏览器或者postman访问。
http://localhost:8080/user/getAllUsers 结果如下:

结果1.png

http://localhost:8080/user/getUser?id=2 结果如下:
结果2.png

6 打包

点击左下角,在弹出的地方点击右边的Maven Projects,然后展开Lifecycle,双击package。然后就能在webapp下面看见war包,把war包放到tomcat下面的webapp里面,启动tomcat就能访问。注意这样访问要加上artifactid,示例:http://localhost:8080/SSM/user/getAllUsers

打包.png

【SSM框架从零开始】系列文章链接:
IntelliJ IDEA搭建最简单的Spring MVC项目
IntelliJ IDEA下Spring MVC数据库配置与增删改查开发
使用Mybatis-Generator自动生成Dao、Model层相关代码
IntelliJ IDEA搭建SSM框架

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,099评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,355评论 6 343
  • 我是在黎明开始苏醒夜雨偷偷地下又偷偷地钻进土里落到无土的地方就拼命地流流着掉下无情的屋檐流着汇成激动的水流流着就在...
    footprint123阅读 260评论 1 2
  • 开头:一天傍晚时分,站在罗生门下的一个仆人等着雨住下来。 结尾:他只有在幽暗中挨着时光,直好像是将一把崩了刃的细剑...
    公子白洛阅读 372评论 0 0
  • 每个人的体质不同,所以大家所需要的睡眠时间也不同,但相同的是睡眠周期,我们恢复体力的黄金时间段就是在深睡期,所以,...
    Bradywbs阅读 204评论 0 1