不知不自觉,工作也两年多了,由于公司一直用的是ssh框架,所以所学也一直是ssh。直到有一天,服务器被攻击,tomcat目录下总有莫名其妙的一些文件,这些文件通过远程ftp下载了一些病毒和木马,服务器一度因为带宽被耗尽而挂掉。经过两三天的摸索,终于找出罪魁祸首就是Struts的漏洞,由于当时使用的Struts的版本较为低,导致被黑客利用。虽然后来花时间把Struts升级了,这次攻击也解除了。但是Struts的安全性确实堪忧,在加上目前多数公司都转向ssm框架,所以便决定花一些时间来学习。
主要目的是将之前做过的项目一步一步从ssh平滑地过度到ssm,通过项目来学习。
今天就先来搭建一下ssm框架。
关于spring,mybatis的基础知识在本文中就不再详细介绍,理论性的东西可以在实践到一定程度回过头去细细琢磨,现在的目标是搭建出一个简单的框架。
1.第一步,新建一个maven的web项目。关于如何搭建maven环境和新建maven项目,在之前的随笔中有写,此处就不再赘述。
将该项目起名为m_gecko,gecko是守宫的意思,是本人很喜欢的一种小宠物,故以此命名。
2.第二步,添加项目所需要的jdk,也就是在maven的porm.xml添加dependency。主要用到spring和mybatis的几个jar包,反正一个一个加,如果运行不起来再去找。
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.m_gecko</groupId>
<artifactId>m_gecko</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>m_gecko Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.5.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.7</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<!-- 打印日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.9</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.9</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 其他 -->
<!-- jsp标签 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- net.sf.json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- websocket -->
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
<build>
<finalName>m_gecko</finalName>
</build>
</project>
3.既然是web项目,肯定需要用到数据库,新建一个mysql数据库,起名gecko,新建一张表,起名t_gecko,表数据如下所示。
4.之前学hibernate,知道orm工具可以把数据库对应的数据映射为java对象,mybatis其实也大同小异,这边介绍一种方法来实现。
去http://download.csdn.net/detail/u012909091/7206091这个地址下载mybatis的jar包和文件,下载后的文件如下图所示。
接下来就是修改generatorConfig.xml这个配置文件,修改后的文件如下所示。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- 数据库驱动--> <classPathEntry location="mysql-connector-java-5.1.25-bin.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--数据库链接URL,用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/gecko" userId="xdx" password="xxxxxxx"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置--> <javaModelGenerator targetPackage="com.m_gecko.entity" targetProject="src"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="com.m_gecko.entity" targetProject="src"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.m_gecko.dao" targetProject="src"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--> <table tableName="t_gecko" domainObjectName="TGecko" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
主要是修改几个地方,如数据库登录名,密码,生成文件存放的包,数据库名,映射文件名等等,配置中写的很清楚了,大家根据自己的实际情况填写即可。
写完配置文件后,cmd进入lib目录下,执行:Java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite 这句指令,就可以生成TGecko.java文件,TGeckoMapper.xml文件还有一个TGeckoMapper.java文件,其中TGeckoMapper.java是一个dao接口,我这边用不着它,只需要前面两个文件。
5.新建包,在src.main.java包下新建项目需要的包。分别新建com.m_gecko.controller,com.m_gecko.service,com.m_gecko.dao,com.m_gecko.entity,com.m_gecko.util,同时新建了com.m_gecko.interceptor,这些包的作用顾名思义,今后也会一一说明。
将上一步生成的TGecko.java和TGeckoMapper.xml文件拷贝到com.m_gecko.entity文件夹下。
这两个文件的源码如下
TGecko.java
package com.m_gecko.entity; import java.util.Date; public class TGecko { private Integer geckoId; private Integer geckoType; private String geckoName; private String picUrl; private Date createTime; private Date updateTime; private Integer isDel; public Integer getGeckoId() { return geckoId; } public void setGeckoId(Integer geckoId) { this.geckoId = geckoId; } public Integer getGeckoType() { return geckoType; } public void setGeckoType(Integer geckoType) { this.geckoType = geckoType; } public String getGeckoName() { return geckoName; } public void setGeckoName(String geckoName) { this.geckoName = geckoName == null ? null : geckoName.trim(); } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl == null ? null : picUrl.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getIsDel() { return isDel; } public void setIsDel(Integer isDel) { this.isDel = isDel; } }
TgeckoMapper.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="TGeckoMapper"> <resultMap id="BaseResultMap" type="Gecko"> <id column="gecko_id" property="geckoId" jdbcType="INTEGER" /> <result column="gecko_type" property="geckoType" jdbcType="INTEGER" /> <result column="gecko_name" property="geckoName" jdbcType="VARCHAR" /> <result column="pic_url" property="picUrl" jdbcType="VARCHAR" /> <result column="create_time" property="createTime" jdbcType="TIMESTAMP" /> <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" /> <result column="is_del" property="isDel" jdbcType="INTEGER" /> </resultMap> <!-- 这个map只获取三个字段gecko_id,gecko_type,gecko_name --> <resultMap id="geckoNameMap" type="Gecko"> <id column="gecko_id" property="geckoId" jdbcType="INTEGER" /> <result column="gecko_type" property="geckoType" jdbcType="INTEGER" /> <result column="gecko_name" property="geckoName" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List"> gecko_id, gecko_type, gecko_name, pic_url, create_time, update_time, is_del </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from t_gecko where gecko_id = #{geckoId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from t_gecko where gecko_id = #{geckoId,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="Gecko"> insert into t_gecko (gecko_id, gecko_type, gecko_name, pic_url, create_time, update_time, is_del) values (#{geckoId,jdbcType=INTEGER}, #{geckoType,jdbcType=INTEGER}, #{geckoName,jdbcType=VARCHAR}, #{picUrl,jdbcType=VARCHAR}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}, #{isDel,jdbcType=INTEGER}) </insert> <insert id="insertSelective" parameterType="Gecko"> insert into t_gecko <trim prefix="(" suffix=")" suffixOverrides=","> <if test="geckoId != null"> gecko_id, </if> <if test="geckoType != null"> gecko_type, </if> <if test="geckoName != null"> gecko_name, </if> <if test="picUrl != null"> pic_url, </if> <if test="createTime != null"> create_time, </if> <if test="updateTime != null"> update_time, </if> <if test="isDel != null"> is_del, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="geckoId != null"> #{geckoId,jdbcType=INTEGER}, </if> <if test="geckoType != null"> #{geckoType,jdbcType=INTEGER}, </if> <if test="geckoName != null"> #{geckoName,jdbcType=VARCHAR}, </if> <if test="picUrl != null"> #{picUrl,jdbcType=VARCHAR}, </if> <if test="createTime != null"> #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateTime != null"> #{updateTime,jdbcType=TIMESTAMP}, </if> <if test="isDel != null"> #{isDel,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="Gecko"> update t_gecko <set> <if test="geckoType != null"> gecko_type = #{geckoType,jdbcType=INTEGER}, </if> <if test="geckoName != null"> gecko_name = #{geckoName,jdbcType=VARCHAR}, </if> <if test="picUrl != null"> pic_url = #{picUrl,jdbcType=VARCHAR}, </if> <if test="createTime != null"> create_time = #{createTime,jdbcType=TIMESTAMP}, </if> <if test="updateTime != null"> update_time = #{updateTime,jdbcType=TIMESTAMP}, </if> <if test="isDel != null"> is_del = #{isDel,jdbcType=INTEGER}, </if> </set> where gecko_id = #{geckoId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="Gecko"> update t_gecko set gecko_type = #{geckoType,jdbcType=INTEGER}, gecko_name = #{geckoName,jdbcType=VARCHAR}, pic_url = #{picUrl,jdbcType=VARCHAR}, create_time = #{createTime,jdbcType=TIMESTAMP}, update_time = #{updateTime,jdbcType=TIMESTAMP}, is_del = #{isDel,jdbcType=INTEGER} where gecko_id = #{geckoId,jdbcType=INTEGER} </update> <select id="listGecko" resultMap="BaseResultMap"> select <include refid="Base_Column_List"></include> from t_gecko where is_del =0 ORDER BY gecko_id </select> <select id="listGeckoByPm" resultMap="BaseResultMap" parameterType="pm"> select <include refid="Base_Column_List"></include> from t_gecko where is_del =0 and gecko_type = #{type,jdbcType=INTEGER} and is_del = #{isDel,jdbcType=INTEGER} ORDER BY gecko_id </select> <select id="listGeckoByPm2" resultMap="geckoNameMap" parameterType="pm"> select <include refid="Base_Column_List"></include> from t_gecko where is_del =0 and gecko_type = #{type,jdbcType=INTEGER} and is_del = #{isDel,jdbcType=INTEGER} ORDER BY gecko_id </select> </mapper>
TgeckoMapper.xml文件中有部分方法是我后续添加进去的,后面会说到。还有一个需要注意的地方,是mapper namespace="TGeckoMapper"这条语句,这是该配置文件的唯一标识。我的理解是,这个文件的作用是把我们在程序运行过程中所需要用到的sql语句都写在这里,然后我们再dao中就可以直接调用了。
6.接下来是配置mybatis的配置文件,在resource包中新建mybatis-config.xml文件,文件如下。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="true" /><!-- 全局映射器启用缓存 --> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> </settings> <typeAliases> <typeAlias type="com.m_gecko.entity.TGecko" alias="Gecko"/> <!-- 辅助类 --> <typeAlias type="com.m_gecko.util.ParamModel" alias="pm"/> </typeAliases> </configuration>
注意这个文件的主要作用是配置实体类的别名。<typeAlias type="com.m_gecko.entity.TGecko" alias="Gecko"/>这句代码将为com.m_gecko.entity.TGecko设置别名为Gecko。
7.还有一步也是最重要的一步,就是编写spring的配置文件,在resource包中新建xml文件,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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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/spring-tx.xsd "> <!-- 启用注解 --> <context:annotation-config /> <!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 --> <context:component-scan base-package="com.m_gecko"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- <context:component-scan base-package="com.m_gecko.*.service" /> --> <aop:aspectj-autoproxy proxy-target-class="true" /> <!-- 读取properties文件 参数配置 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!-- ====================数据源1==================== --> <!-- sql会话模版 --> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory" /> </bean> <!-- 配置mybatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 数据源 --> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- mapper扫描 --> <property name="mapperLocations" value="classpath:com/m_gecko/entity/*.xml"></property> </bean> <!-- 阿里 druid数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <!-- 数据库基本信息配置 --> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <property name="driverClassName" value="${driverClassName}" /> <property name="filters" value="${filters}" /> <!-- 最大并发连接数 --> <property name="maxActive" value="${maxActive}" /> <!-- 初始化连接数量 --> <property name="initialSize" value="${initialSize}" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${maxWait}" /> <!-- 最小空闲连接数 --> <property name="minIdle" value="${minIdle}" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${validationQuery}" /> <property name="testWhileIdle" value="${testWhileIdle}" /> <property name="testOnBorrow" value="${testOnBorrow}" /> <property name="testOnReturn" value="${testOnReturn}" /> <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="${removeAbandoned}" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="${logAbandoned}" /> </bean> <!-- 事物处理 --> <aop:config> <aop:pointcut id="pc" expression="execution(* com.m_gecko.service..*(..))" /> <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> </tx:attributes> </tx:advice> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
注意里面引用了jdbc的properties包,内容如下。
#数据源1 url:jdbc:mysql://xxx.xxx.xxx.xxx:3306/gecko?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&zeroDateTimeBehavior=convertToNull driverClassName:com.mysql.jdbc.Driver username:xxxx password:xxxxxxxxx filters:stat maxActive:20 initialSize:1 maxWait:60000 minIdle:10 maxIdle:15 timeBetweenEvictionRunsMillis:60000 minEvictableIdleTimeMillis:300000 validationQuery:SELECT 'x' testWhileIdle:true testOnBorrow:false testOnReturn:false maxOpenPreparedStatements:20 removeAbandoned:true removeAbandonedTimeout:1800 logAbandoned:true
这样就完成了一些基本项目框架的搭建,但是现在项目还无法运行起来。文章篇幅过长,所以留在下一篇来讲,下一篇文章会写一个简单的demo,集成spring和mybatis.