前言
开发环境:Eclipse Mars + Maven + JDK 1.7 + Tomcat 7 + MySQL
主要框架:Spring + Spring MVC + Mybatis
目的:快速上手搭建SSM开发环境,熟悉客户端请求到数据库操作的流程。
准备工作
本文以“人”Person对象为例,所以首先在数据库中建一张表。这里用的Navicat for MySql,新建一个名为ssm的数据库,然后在库中新建一张名为TBL_PERSON的表,3个字段,分别为主键id,姓名name,性别gender,都为字符串类型。这里主键id没有采用自增,而是用UUID随机字符串。数据表概要如图所示。
新建一个maven web项目,工程结构如下和pom.xml配置如下,并创建一个pojo类Person
<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.mmm</groupId> <artifactId>ssm-web</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>ssm-web Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL标签类 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.0</version> </dependency> </dependencies> <build> <finalName>ssm-web</finalName> </build> </project>
package com.mmm.pojo; /** * Person实体类 * */ public class Person { private String id; private String name; private String gender; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
配置篇
1.Spring 集成Mybatis配置文件以及应用(application-root.xml + maybatis-config.xml + jsbc.properties)
<?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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 引入数据库配置参数文件jdbc.properties --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- Spring会扫描指定包下的bean注解例如@Controller、@Service等 --> <context:component-scan base-package="com.mmm" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- spring和MyBatis整合 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapper.xml文件 --> <property name="mapperLocations" value="classpath:com/mmm/mapper/*.xml"></property> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!-- Mapper接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mmm.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> </beans>
<?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> <!-- 这里可以定义类的别名,在mapper.xml文件中应用会方便很多 --> <typeAliases> <typeAlias alias="person" type="com.mmm.pojo.Person" /> </typeAliases> </configuration>
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf-8 jdbc.username=root jdbc.password=123456
2.Spring MVC配置(application-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: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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描开启 --> <context:component-scan base-package="com.mmm.web" /> <mvc:annotation-driven/> <!-- Spring MVC视图解析配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
3.PersonMapper映射配置文件(personMapper.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.mmm.mapper.PersonMapper"> <resultMap type="person" id="personResultMap" > <id property="id" column="id"></id> <result property="name" column="name"></result> <result property="gender" column="gender"></result> </resultMap> <!-- 新增一条记录 --> <insert id="insert" parameterType="person" > <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String"> select replace(uuid(),'-','') from dual </selectKey> insert into `TBL_PERSON` values (#{id},#{name},#{gender}) </insert> <!-- 删除一条记录 --> <delete id="delete"> delete from `TBL_PERSON` where id = #{id} </delete> <!-- 更新一条记录 --> <update id="update" parameterType="person"> update `TBL_PERSON` set name = #{name}, gender = #{gender} </update> <!-- 查找所有记录 --> <select id="selectAll" resultMap="personResultMap"> select * from `TBL_PERSON` </select> <!-- 根据主键id查找记录 --> <select id="selectById" resultType="person"> select * from `TBL_PERSON` where id = #{id} </select> </mapper>
4.web.xml配置(web.xml)
<?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" version="3.0"> <!-- Spring的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application-root.xml</param-value> </context-param> <!-- 编码过滤器 --> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring MVC 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:application-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
代码篇
1.mapper包下(com.mmm.mapper)
package com.mmm.mapper; import java.util.List; import com.mmm.pojo.Person; public interface PersonMapper { //新增一个Person对象 void insert(Person p); //根据主键id删除Person对象 void deleteById(String id); //修改一个person对象 void update(Person p); //根据主键id查找Person对象 Person selectById(String id); //查找所有Person对象,返回集合类型 List<Person> selectAll(); }
2.service包下(com.mmm.service)
package com.mmm.service; import java.util.List; import com.mmm.pojo.Person; public interface PersonService { //新增一个Person对象 void insert(Person p); //根据主键id删除Person对象 void deleteById(String id); //修改一个person对象 void update(Person p); //根据主键id查找Person对象 Person selectById(String id); //查找所有Person对象,返回集合类型 List<Person> selectAll(); }
package com.mmm.service; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.mmm.mapper.PersonMapper; import com.mmm.pojo.Person; @Service public class PersonServiceImpl implements PersonService { @Resource PersonMapper personMapper; @Override public void insert(Person p) { personMapper.insert(p); } @Override public void deleteById(String id) { personMapper.deleteById(id); } @Override public void update(Person p) { personMapper.update(p); } @Override public Person selectById(String id) { return personMapper.selectById(id); } @Override public List<Person> selectAll() { return personMapper.selectAll(); } }
3.web包下(com.mmm.web)
package com.mmm.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.mmm.pojo.Person; import com.mmm.service.PersonService; @Controller @RequestMapping("person") public class PersonController { @Autowired PersonService personService; /** * 这里return的字符串"mvc"加上前面Spring MVC配置文件中视图解析配置的前缀"/WEB-INF/views/"和后缀".jsp", * 构成了要请求转发要跳转到的页面路径,从根路径webapp下开始,即为/WEB-INF/views/mvc.jsp * */ @RequestMapping(value="mvc") public String testMvc() { return "mvc";// } /** * 这里@ResponseBody代表方法是直接返回一个json数据回前端, * 注意Spring mvc配置文件中不要漏掉<mvc:annotation-driven/> * */ @RequestMapping(value="list") @ResponseBody public List<Person> findAll() { List<Person> list = personService.selectAll(); return list;//这里通过前端返回的json数据查看到完整数据 } /** * 其中@PathVariable用来获得请求url中的动态参数 * */ @RequestMapping(value="one/{id}") @ResponseBody public Person findOne(@PathVariable("id") String id) { return personService.selectById(id); } }
至此,ssm开发基本环境已经初步搭建好
测试篇
1.测试mybatis封装的持久层(这里以获取所有TBL_PERSON表的NAME字段值为例)
package com.test; import java.util.List; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mmm.pojo.Person; import com.mmm.service.PersonService; public class TestDb { @SuppressWarnings("resource") @Test public void testDb() { ApplicationContext context = new ClassPathXmlApplicationContext("application-root.xml"); PersonService bean = (PersonService) context.getBean("personServiceImpl"); List<Person> list = bean.selectAll(); for(Person p:list) { System.out.println(p.getName()); } } }
结果如下
2.测试Spring MVC部分
Tomcat启动项目,地址栏输入http://localhost:8080/ssm-web/person/list,拿到如下图所示数据即为成功
反省篇
最后,SSM开发环境基本搭建完毕,既然是基本,还存在许多没有尽量完善的地方。首先Mybatis部分,这里是从零开始,也没用到什么逆向工程之类的,都自己手写,便于理解,然后关联映射只写了简单的单表操作,关联的没写到,另外单表简单操作,在这里与spring集成过程中事务也没有进行事务管理的配置等。Spring MVC方面更是简陋了点,不过实际工作开发中,比较核心的有视图解析后转发到相应页面和json返回数据,大多问题是在考虑怎样实现业务逻辑。很多细节没有写出来,然后有些原理性的东西自己也还需要不断理解学习,之后应该写一些关键细节描述类的总结文。