简介:
SSM框架是Spring,SpringMVC 和Mybatis框架的整合,是标准的MVC模式,将整个系统划分为表现层,controller层,service层,dao层四层。
Spring实现对业务对象的管理,SpirngMVC负责请求的转发和视图管理,Mybatis作为数据对象的持久化引擎。
简单案例:
一,创建web项目,建好项目结构目录(controller,service,mapper等目录),引入所需的jar包并配置tomcat
这里放上最终的项目结构:
pom.xml(继承于父工程,没有写版本信息)
<?xml version="1.0" encoding="UTF-8"?> <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/xsd/maven-4.0.0.xsd"> <parent> <artifactId>project_parent</artifactId> <groupId>com.com.zy</groupId> <version>1.0-SNAPSHOT</version> <relativePath>../project_parent/pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>child_ssmDemo</artifactId> <packaging>war</packaging> <dependencies> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <!--spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <!--mybatis-spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </dependency> <!--jsp相关--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--Druid连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <!--json处理工具包--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <!--log--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </dependency> <!-- Apache工具组件 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> </dependency> <!--PageHelper--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> </dependency> <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> </dependency> </dependencies> <build> <plugins> <!--tomcat--> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>8080</port> </configuration> </plugin> </plugins> </build> </project>
pom.xml
dbconfig.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/temp_db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true jdbc.username=root jdbc.password=root
dbconfig.properties
log4j.properties
log4j.rootLogger=DEBUG,A1 log4j.logger.com.taotao = DEBUG log4j.logger.org.mybatis = DEBUG log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
log4j.properties
二,准备数据库表及数据
CREATE TABLE `tb_user` ( `id` BIGINT(20) NOT NULL AUTO_INCREMENT, `username` VARCHAR(100) DEFAULT NULL COMMENT ‘用户名‘, `password` VARCHAR(100) DEFAULT NULL COMMENT ‘密码‘, `name` VARCHAR(100) DEFAULT NULL COMMENT ‘姓名‘, `age` INT(10) DEFAULT NULL COMMENT ‘年龄‘, `sex` TINYINT(1) DEFAULT NULL COMMENT ‘性别,1男性,2女性‘, `birthday` DATE DEFAULT NULL COMMENT ‘出生日期‘, `created` DATETIME DEFAULT NULL COMMENT ‘创建时间‘, `updated` DATETIME DEFAULT NULL COMMENT ‘更新时间‘, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) INSERT INTO `tb_user` VALUES (NULL, ‘zhangxueyou‘, ‘123456‘, ‘张学友‘, ‘30‘, ‘1‘, ‘1984-08-08‘, ‘2014-09-19 16:56:04‘, ‘2014-09-21 11:24:59‘); INSERT INTO `tb_user` VALUES (NULL, ‘liudehua‘, ‘123456‘, ‘刘德华‘, ‘21‘, ‘2‘, ‘1991-01-01‘, ‘2014-09-19 16:56:04‘, ‘2014-09-19 16:56:04‘); INSERT INTO `tb_user` VALUES (NULL, ‘guofucheng‘, ‘123456‘, ‘郭富城‘, ‘22‘, ‘2‘, ‘1989-01-01‘, ‘2014-09-19 16:56:04‘, ‘2014-09-19 16:56:04‘); INSERT INTO `tb_user` VALUES (NULL, ‘liming‘, ‘123456‘, ‘黎明‘, ‘20‘, ‘1‘, ‘1988-09-01‘, ‘2014-09-19 16:56:04‘, ‘2014-09-19 16:56:04‘); INSERT INTO `tb_user` VALUES (NULL, ‘linghuchong‘, ‘123456‘, ‘令狐冲‘, ‘28‘, ‘1‘, ‘1985-01-01‘, ‘2014-09-19 16:56:04‘, ‘2014-09-19 16:56:04‘); INSERT INTO `tb_user` VALUES (NULL, ‘zhangsanfeng‘, ‘123456‘, ‘张三丰‘, ‘23‘, ‘1‘, ‘1988-08-08‘, ‘2014-09-20 11:41:15‘, ‘2014-09-20 11:41:15‘); INSERT INTO `tb_user` VALUES (NULL, ‘lixunhua‘, ‘123456‘, ‘李寻欢‘, ‘23‘, ‘1‘, ‘1988-08-08‘, ‘2014-09-20 11:41:15‘, ‘2014-09-20 11:41:15‘); INSERT INTO `tb_user` VALUES (NULL, ‘sunyanzi‘, ‘123456‘, ‘孙燕姿‘, ‘23‘, ‘1‘, ‘1988-08-08‘, ‘2014-09-20 11:41:15‘, ‘2014-09-20 11:41:15‘);
创建表及插入数据
三,先整合spring和mybatis
3.1 分析:
1. mybatis框架操作数据库 需要 sqlSessionFactory 2. sqlSessionFactory 需要 连接池 datasource 3. sqlSessionFactory的可以交给spring管理 4. mapper接口的实现也可以交给spring去管理 5. 可以在spring配置中关联mybatis的配置文件
3.2 创建User的JavaBean类:
package com.zy.model; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; public class User { private Long id; // 用户名 private String userName; // 密码 private String password; // 姓名 private String name; // 年龄 private Integer age; // 性别,1男性,2女性 private Integer sex; // 出生日期 @DateTimeFormat(pattern = "yyyy-MM-dd") private Date birthday; // 创建时间 private Date created; // 更新时间 private Date updated; public Long getId() { return id; } public void setId(Long 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 getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Date getUpdated() { return updated; } public void setUpdated(Date updated) { this.updated = updated; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", name=" + name + ", age=" + age + ", sex=" + sex + ", birthday=" + birthday + ", created=" + created + ", updated=" + updated + "]"; } }
User JavaBean
3.2 创建mapper接口,并添加查询所有信息的方法:
public interface UserMapper { /** * 获取所有User集合 */ public List<User> getAllUserList(); }
3.3 在resource/mybatis下创建mybatis配置文件mybatis-config.xml:
<?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> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
3.4 在resource/spring下创建spring配置文件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"> <!--引入外部数据库配置文件--> <context:property-placeholder location="classpath:dbconfig.properties"/> <!--配置Druid数据库--> <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource"> <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> <!--mybatis依赖的 sqlsessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--注入数据库连接--> <property name="dataSource" ref="druidDataSource"/> <!--关联mybatis配置文件--> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <!--扫描domain包 代替mybatis起别名--> <property name="typeAliasesPackage" value="com.zy.domain"/> <!--关联mapper.xml文件--> <property name="mapperLocations" value="classpath:mybatis/mapper/**/*Mapper.xml"/> </bean> <!--扫描mapper接口包 srping使用动态代理创建mapper接口实现类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zy.mapper"></property> </bean> </beans>
3.5 在resource/mybatis/mapper下创建UserMapper对应的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"> <mapper namespace="com.zy.mapper.UserMapper"> <update id="editUserName"> update tb_user set name=#{name} where id=#{id} </update> </mapper>
3.6 mapper单元测试:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring/applicationContext.xml") public class UserMapperTest { @Value("#{userMapper}") UserMapper userMapper; @Test public void editUserName() throws Exception { userMapper.editUserName(1, "张三三"); } }
四,添加业务层并添加事务
4.1 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" 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/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:property-placeholder location="classpath:dbconfig.properties"/> <!--配置Druid数据库--> <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource"> <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> <!--mybatis依赖的 sqlsessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--注入数据库连接--> <property name="dataSource" ref="druidDataSource"/> <!--关联mybatis配置文件--> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/> <!--扫描domain包 代替mybatis起别名--> <property name="typeAliasesPackage" value="com.zy.domain"/> <!--关联mapper.xml文件--> <property name="mapperLocations" value="classpath:mybatis/mapper/**/*Mapper.xml"/> </bean> <!--扫描mapper接口包 srping使用动态代理创建mapper接口实现类--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zy.mapper"></property> </bean> <!--实例化 事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="druidDataSource"/> </bean> <!--开启事务注解--> <tx:annotation-driven transaction-manager="transactionManager"/> <!--扫描注解 业务层交给spring管理--> <context:component-scan base-package="com.zy"></context:component-scan> </beans>
4.2 创建业务类UserService添加注解并配置扫描注解 将业务层交给spring管理(已经在上面提前加上了):
@Service public class UserService { @Value("#{userMapper}") private UserMapper userMapper; //同时修改两个id的name @Transactional public void eidtUserNames(long id1, String name1, long id2, String name2) { userMapper.editUserName(id1, name1); int i = 1 / 0;//制造异常 userMapper.editUserName(id2, name2); } }
4.3 单元测试:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:spring/applicationContext.xml") public class UserServiceTest { @Value("#{userService}") private UserService userService; @Test public void eidtUserNames() throws Exception { userService.eidtUserNames(1, "张影帝", 2, "刘天王"); } }
五,在上面的基础上整合SpringMVC
5.1 在web.xml中配置监听器,以便在tomcat启动后直接实例化spring容器:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!--指定spring配置文件的位置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext*.xml</param-value> </context-param> <!--tomcat启动后实例化spring容器的监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
5.2 在web.xml中配置DispatcherServlet信息:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!--指定spring配置文件的位置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext*.xml</param-value> </context-param> <!--tomcat启动后实例化spring容器的监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--整合springmvc--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加载springmvc的配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext_springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <!--拦截jsp以外的内容--> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
5.3 添加并配置5.2中整合mvc的配置文件applicationContext_springmvc.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:mvc="http://www.springframework.org/schema/mvc" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--HandlerMapping和HandlerAdapter--> <mvc:annotation-driven/> <!--扫描controller包--> <context:component-scan base-package="com.zy.controller"/> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前缀--> <property name="prefix" value="/WEB-INF/views/"/> <!--后缀--> <property name="suffix" value=".jsp"/> </bean> <!--对于静态资源不拦截--> <mvc:default-servlet-handler/> </beans>
5.4 创建WEB-INF/views文件夹并创建UserController:
@Controller @RequestMapping("/user") public class UserController { @Value("#{userService}") private UserService userService; @RequestMapping("/editUsers") public ModelAndView editUserNames() { ModelAndView mv = new ModelAndView("success"); userService.eidtUserNames(1, "张天王", 2, "刘影帝"); mv.addObject("msg", "success"); return mv; } }
运行tomcat访问http://localhost:8080/user/editUsers,然后看一下数据库数据是否已经改变即可。
再来把User列表的json数据信息返回到页面:
UserMapper添加方法:
public interface UserMapper { //根据id修改名字 public void editUserName(@Param("id") long id, @Param("name") String name); //获取user列表 public List<User> getUserList(); }
UserMapper.xml添加sql:
<?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.zy.mapper.UserMapper"> <update id="editUserName"> update tb_user set name=#{name} where id=#{id} </update> <select id="getUserList" resultType="User"> select * from tb_user </select> </mapper>
UserService添加获取list方法:
@Service public class UserService { @Value("#{userMapper}") private UserMapper userMapper; //同时修改两个id的name @Transactional public void eidtUserNames(long id1, String name1, long id2, String name2) { userMapper.editUserName(id1, name1); //int i = 1 / 0; userMapper.editUserName(id2, name2); } //获取userlist数据 public List<User> getUserList() { return userMapper.getUserList(); } }
UserController添加对应的controller方法:
@Controller @RequestMapping("/user") public class UserController { @Value("#{userService}") private UserService userService; @RequestMapping("/editUsers") public ModelAndView editUserNames() { ModelAndView mv = new ModelAndView("success"); userService.eidtUserNames(1, "张天王", 2, "刘影帝"); mv.addObject("msg", "success"); return mv; } @RequestMapping("/userList") @ResponseBody public ModelAndView getUserList() { ModelAndView mv = new ModelAndView("user_list"); mv.addObject("userList", userService.getUserList().toString()); return mv; } }
运行tomcat访问http://localhost:8080/user/userList:
以上。
原文地址:https://www.cnblogs.com/Alex-zqzy/p/9343535.html