本人在学习Maven之余,为了深入了解Maven的用法,决定创建一个SSM整合实例。项目是自己实际搭建,真实可用。
-
技术介绍
SSM(Spring+SpringMVC+Mybatis)
Spring是一种轻量级框架,这是众所周知的,开发者只需要把一些常用的如日志,事务管理在配置文件中申明,能大大降低代码的耦合,减少代码侵入。他的核心是 IOC(控制反转)和AOP(面向切面编程),具体大家想了解深入可以上网查阅,这里不再多讲。
SpringMVC顾名思义就是运用Spring框架使用MVC思想实现,他的核心就是前端控制器(DispatcherServlet),它的工作原理是:
1、客户端发出一个http请求给web服务器,web服务器对http请求进行解析,如果匹配DispatcherServlet的请求映射路径(在web.xml中指定),web容器将请求转交给
DispatcherServlet.
2、DipatcherServlet接收到这个请求之后将根据请求的信息(包括URL、Http方法、请求报文头和请求参数Cookie等)以及HandlerMapping的配置找到处理请求的处理 器(Handler)。
3-4、DispatcherServlet根据HandlerMapping找到对应的Handler,将处理权交给Handler(Handler将具体的处理进行封装),再由具体的HandlerAdapter对Handler进行 具体的调用。
5、Handler对数据处理完成以后将返回一个ModelAndView()对象给DispatcherServlet。
6、Handler返回的ModelAndView()只是一个逻辑视图并不是一个正式的视图,DispatcherSevlet通过ViewResolver将逻辑视图转化为真正的视图View。
7、Dispatcher通过model解析出ModelAndView()中的参数进行解析最终展现出完整的view并返回给客户端。
Mybatis是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对 配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
- 数据库创建
这里是MySQL数据库,数据库表创建如下图:
CREATE TABLE tb_user( id int(11) NOT NULL AUTO_INCREMENT, user_name varchar(40) NOT NULL, password varchar(40) NOT NULL, age int(4) NOT NULL, PRIMARY KEY(id)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
- SSM整合步骤
完整项目整合如下图所示:
1.创建Maven的Web项目(这个在上一篇文章已经讲解了,这里就不再多讲)
2.配置pom.xml,代码如下:
<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>cn.temp</groupId> <artifactId>maven-web-demo02</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>maven-web-demo02 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <srping.version>4.0.2.RELEASE</srping.version> <mybatis.version>3.2.8</mybatis.version> <slf4j.version>1.7.12</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- java ee包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <!-- spring框架包 start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${srping.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${srping.version}</version> </dependency> <!-- spring框架包 end --> <!-- mybatis框架包 start --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- mybatis框架包 end --> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- jstl标签类 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</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> <!-- log END --> <!-- Json --> <!-- 格式化对象,方便输出日志 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.6</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上传组件包 start --> <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.10</version> </dependency> <!-- 上传组件包 end --> </dependencies> <build> <finalName>maven-web-demo02</finalName> </build> </project>
3.创建jdbc.properties文件
driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/orcl username=root password=123qweasd initialSize=0 maxActive=20 maxIdle=20 minIdle=1 maxWait=60000
4.创建日志属性文件
#u5B9Au4E49LOGu8F93u51FAu7EA7u522B log4j.rootLogger=INFO,Console,File #u5B9Au4E49u65E5u5FD7u8F93u51FAu76EEu7684u5730u4E3Au63A7u5236u53F0 log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out #u53EFu4EE5u7075u6D3Bu5730u6307u5B9Au65E5u5FD7u8F93u51FAu683Cu5F0FuFF0Cu4E0Bu9762u4E00u884Cu662Fu6307u5B9Au5177u4F53u7684u683Cu5F0F log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n #u6587u4EF6u5927u5C0Fu5230u8FBEu6307u5B9Au5C3Au5BF8u7684u65F6u5019u4EA7u751Fu4E00u4E2Au65B0u7684u6587u4EF6 log4j.appender.File = org.apache.log4j.RollingFileAppender #u6307u5B9Au8F93u51FAu76EEu5F55 log4j.appender.File.File = logs/ssm.log #u5B9Au4E49u6587u4EF6u6700u5927u5927u5C0F log4j.appender.File.MaxFileSize = 10MB # u8F93u51FAu6240u4EE5u65E5u5FD7uFF0Cu5982u679Cu6362u6210DEBUGu8868u793Au8F93u51FADEBUGu4EE5u4E0Au7EA7u522Bu65E5u5FD7 log4j.appender.File.Threshold = ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n
5.接下来创建Spring和MyBatis整合文件
<?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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.sgcc.user" > <!-- 不扫描@Controller注解的类--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/sgcc/user/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 动态代理实现 不用写dao的实现类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.sgcc.user.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
6.创建SpringMVC文件,如下代码
<?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-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描该包 @controller注解的类--> <context:component-scan base-package="com.sgcc.user.controller"/> <!-- 静态资源处理 --> <mvc:default-servlet-handler/> <!--自动注册 RequestMappingHandlerMapping、RequestMappingHandlerAdapter 等bean --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
7.接下来就是各个业务文件了,如下图所示:
8.创建UserController文件,如下图所示:
package com.sgcc.user.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.sgcc.user.pojo.User;
import com.sgcc.user.service.UserService;
@Controller
public class UserController {
/**
* 使用@Autowired也可以,@Autowired默认按类型装配
* @Resource 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。
*/
@Resource
private UserService userService;
/**
* 测试查询
*
* @param id
* @param model
* @return
*/
@RequestMapping("/showUser")
public String testtoshowUser(@RequestParam(value = "id") Integer id, Model model) {
System.out.println("id:" + id);
User user = userService.getUserById(id);
model.addAttribute("user", user);
return "showUser";
}
/**
* 测试添加数据
*
* @param id
* @param model
* @return
*/
@RequestMapping("/insertUser")
public String testinsertUser() {
User user = new User();
user.setUserName("李清照");
user.setPassword("3232322");
user.setAge(22);
int count = userService.insert(user);
System.out.println("插入" + count + "条数据成功");
return "showUser";
}
}
9.创建UserDao
package com.sgcc.user.dao; import com.sgcc.user.pojo.User; public interface UserDao { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
10.创建UserMapper.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" > <!-- namespace的值就是dao接口的完整路径,就这个demo而言namespace 就是userDao.java的完整路径--> <mapper namespace="com.sgcc.user.dao.UserDao"> <resultMap id="BaseResultMap" type="com.sgcc.user.pojo.User"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List"> id, user_name, password, age </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from tb_user where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from tb_user where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.sgcc.user.pojo.User"> insert into tb_user (id, user_name, password, age) values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}) </insert> <insert id="insertSelective" parameterType="com.sgcc.user.pojo.User"> insert into tb_user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null"> id, </if> <if test="userName != null"> user_name, </if> <if test="password != null"> password, </if> <if test="age != null"> age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null"> #{id,jdbcType=INTEGER}, </if> <if test="userName != null"> #{userName,jdbcType=VARCHAR}, </if> <if test="password != null"> #{password,jdbcType=VARCHAR}, </if> <if test="age != null"> #{age,jdbcType=INTEGER}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.sgcc.user.pojo.User"> update tb_user <set> <if test="userName != null"> user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="password != null"> password = #{password,jdbcType=VARCHAR}, </if> <if test="age != null"> age = #{age,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.sgcc.user.pojo.User"> update tb_user set user_name = #{userName,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, age = #{age,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
12.创建User类
package com.sgcc.user.pojo; public class User { private Integer id; private String userName; private String password; private Integer age; 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 == null ? null : userName.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", age=" + age + "]"; } }
13.创建UserService接口
package com.sgcc.user.service; import com.sgcc.user.pojo.User; public interface UserService { //根据id查找 public User getUserById(Integer userid); //添加一条数据 public int insert(User user); }
14.创建UserServiceImpl实现类
package com.sgcc.user.service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sgcc.user.dao.UserDao; import com.sgcc.user.pojo.User; @Transactional @Service("userService") public class UserServiceImpl implements UserService { /** * 因为没有在spring的文件中显式的声明userService实现类,直接通过getBean得到 userService 会找不到 * 需要显式配置 @Service ("userService"),指定bean的名称 * 相当与<bean id="userService" class="com.jxust.ssm.service.impl.UserServiceImpl"></bean> */ @Resource private UserDao userDao; public User getUserById(Integer userid) { return this.userDao.selectByPrimaryKey(userid); } @Override public int insert(User user) { return this.userDao.insert(user); } }
16.配置程序入口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" id="WebApp_ID" version="3.0"> <display-name>maven-web-demo02</display-name> <!-- 编码过滤器 --> <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> <!-- Spring监听器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--Spring MVC 配置servlet --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
18.创建前端页面,index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="showUser?id=2">ShowUser page</a><br> <a href="insertUser">insertUser </a> </body> </html>
19.创建showUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>测试</title> </head> <body> id:${user.id} <br> userName: ${user.userName} <br> password: ${user.password} <br> age: ${user.age} <br> </body> </html>
20启动服务,如下图所示: