文章目录

  • SSM(spring+springMVC+Mybatis)整合流程简介
    • 项目基础结构搭建
    • spring 整合mybatis
      • 创建MyBatis映射文件
      • 创建Spring配置文件、整合Mybatis到Spring环境中
      • 创建单元测试
    • 整合SpringMVC
      • 数据封装(定义数据交换中间件)
      • 统一异常处理
      • 表现层业务方法处理
    • 注解整合
      • userDao.xml
      • web.xml
      • applicationContext.xml
      • spring -mvc.xml

SSM(spring+springMVC+Mybatis)整合流程简介


项目基础结构搭建

  • 创建项目,项目结构
  • 创建表与实体类
  • 创建三层架构对应的模块、接口与实体类,建立关联关系
    • 数据层接口(代理自动创建实现类)
    • 业务层接口 + 业务层实现类
    • 表现层类

创建项目

创建数据表

CREATE TABLE `user` (`uuid` int(10) NOT NULL AUTO_INCREMENT,`userName` varchar(100) DEFAULT NULL,`password` varchar(100) DEFAULT NULL,`realName` varchar(100) DEFAULT NULL,`gender` int(1) DEFAULT NULL,`birthday` date DEFAULT NULL,PRIMARY KEY (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8CREATE TABLE `student` (`uuid` int(10) NOT NULL AUTO_INCREMENT,`name` varchar(50) DEFAULT NULL,`age` int(3) DEFAULT NULL,`birthday` date DEFAULT NULL,PRIMARY KEY (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

创建实体类
student

package com.zs.domain;import lombok.Data;import java.io.Serializable;
import java.util.Date;@Data
public class Student implements Serializable {private static final long serialVersionUID = 207360847718257908L;private Integer uuid;private String name;private Integer age;private Date birthday;}

user

package com.zs.domain;import lombok.Data;import java.io.Serializable;
import java.util.Date;@Data
public class User implements Serializable {private static final long serialVersionUID = -7584152384912091175L;private Integer uuid;private String userName;private String password;private String realName;private Integer gender;private Date birthday;
}

数据层接口(代理自动创建实现类)

package com.zs.dao;import com.zs.domain.Student;import java.util.List;public interface StudentDao {boolean save(Student student);boolean update(Student student);boolean delete(Integer uuid);Student get(Integer uuid);List<Student> getAll();}
package com.zs.dao;import com.zs.domain.User;import java.util.List;public interface UserDao {boolean save(User user);boolean update(User user);boolean delete(Integer uuid);User get(Integer uuid);List<User> getAll();User getByUserNameAndPassword(String userName,String password);
}

业务层接口 + 实现类


package com.zs.service;import com.zs.domain.Student;import java.util.List;public interface StudentService {boolean save(Student student);boolean update(Student student);boolean delete(Integer uuid);Student get(Integer uuid);List<Student> getAll();
}
package com.zs.service;import com.zs.domain.User;import java.util.List;public interface UserService {boolean save(User user);boolean update(User user);boolean delete(Integer uuid);User get(Integer uuid);List<User> getAll();User login(String userName,String password);
}
package com.zs.service.impl;import com.zs.domain.Student;
import com.zs.service.StudentService;import java.util.List;public class StudentServiceImpl implements StudentService {@Overridepublic boolean save(Student student) {return false;}@Overridepublic boolean update(Student student) {return false;}@Overridepublic boolean delete(Integer uuid) {return false;}@Overridepublic Student get(Integer uuid) {return null;}@Overridepublic List<Student> getAll() {return null;}
}
package com.zs.service.impl;import com.zs.domain.User;
import com.zs.service.UserService;import java.util.List;public class UserServiceImpl implements UserService {@Overridepublic boolean save(User user) {return false;}@Overridepublic boolean update(User user) {return false;}@Overridepublic boolean delete(Integer uuid) {return false;}@Overridepublic User get(Integer uuid) {return null;}@Overridepublic List<User> getAll() {return null;}@Overridepublic User login(String userName, String password) {return null;}
}

spring 整合mybatis

<?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"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>springmvc_ssm</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.8</version></dependency><!--spring环境--><!--spring环境--><!--spring环境--><!--springMVC依赖于spring-context--><!--<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.9.RELEASE</version></dependency>--><!--mybatis环境--><!--mybatis环境--><!--mybatis环境--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.3</version></dependency><!--mysql环境--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency><!--spring整合jdbc--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.1.9.RELEASE</version></dependency><!--spring整合mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.3</version></dependency><!--druid连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.16</version></dependency><!--分页插件坐标--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.1.2</version></dependency><!--springmvc环境--><!--springmvc环境--><!--springmvc环境--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.1.9.RELEASE</version></dependency><!--jackson相关坐标3个--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version></dependency><!--上面的jackson-databind 依赖于下面的--><!--<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.0</version></dependency>--><!--servlet环境--><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><!--其他组件--><!--其他组件--><!--其他组件--><!--junit单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!--spring整合junit--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.1.9.RELEASE</version></dependency></dependencies><repositories><repository><id>aliyun-maven</id><name>aliyun maven</name><url>http://maven.aliyun.com/nexus/content/groups/public/</url></repository></repositories><pluginRepositories><pluginRepository><id>aliyun-maven</id><name>aliyun maven</name><url>http://maven.aliyun.com/nexus/content/groups/public/</url></pluginRepository></pluginRepositories><build><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes><filtering>true</filtering></resource></resources></build>
</project>

创建MyBatis映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zs.dao.UserDao"><!--添加--><insert id="save" parameterType="user">insert into user(userName,password,realName,gender,birthday)values(#{userName},#{password},#{realName},#{gender},#{birthday})</insert><!--删除--><delete id="delete" parameterType="int">delete from user where uuid = #{uuid}</delete><!--修改--><update id="update" parameterType="user">update user set userName=#{userName},password=#{password},realName=#{realName},gender=#{gender},birthday=#{birthday} where uuid=#{uuid}</update><!--查询单个--><select id="get" resultType="user" parameterType="int">select * from user where uuid= #{uuid}</select><!--分页查询--><select id="getAll" resultType="user">select * from user</select><!--登录--><select id="getByUserNameAndPassword" resultType="user" >select * from user where userName=#{userName} and password=#{password}</select></mapper>

创建Spring配置文件、整合Mybatis到Spring环境中

  • 组件扫描

  • SqlSessionFactoryBean

  • 数据源(druid + jdbc.properties)

  • 映射扫描

  • 注解事务

  • 分页插件

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><context:component-scan base-package="com.zs"><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!--整合mybatis--><!--整合mybatis--><!--整合mybatis--><!--整合mybatis--><tx:annotation-driven transaction-manager="txManager"/><!--加载properties文件--><context:property-placeholder location="classpath*:jdbc.properties"/><!--数据源--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--整合mybatis到spring中--><bean class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="typeAliasesPackage" value="com.zs.domain"/><!--分页插件--><property name="plugins"><array><bean class="com.github.pagehelper.PageInterceptor"><property name="properties"><props><!--方言--><prop key="helperDialect">mysql</prop><!--合理化配置--><prop key="reasonable">true</prop></props></property></bean></array></property></bean><!--映射扫描--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.zs.dao"/></bean><!--事务--><bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean>
</beans>

创建单元测试

package com.zs.service;import com.github.pagehelper.PageInfo;
import com.zs.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.Date;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserServiceTest {@Autowiredprivate UserService userService;@Testpublic void testSave(){User user = new User();user.setUserName("Jock");user.setPassword("root");user.setRealName("Jockme");user.setGender(1);user.setBirthday(new Date(333333000000L));userService.save(user);}@Testpublic void testDelete(){User user = new User();userService.delete(3);}@Testpublic void testUpdate(){User user = new User();user.setUuid(1);user.setUserName("Jockme");user.setPassword("root");user.setRealName("JockIsMe");user.setGender(1);user.setBirthday(new Date(333333000000L));userService.update(user);}@Testpublic void testGet(){User user = userService.get(1);System.out.println(user);}@Testpublic void testGetAll(){PageInfo<User> all = userService.getAll(2, 2);System.out.println(all);System.out.println(all.getList().get(0));System.out.println(all.getList().get(1));}@Testpublic void testLogin(){User user = userService.login("Jockme", "root");System.out.println(user);}
}
package com.zs.service.impl;import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zs.dao.UserDao;
import com.zs.domain.User;
import com.zs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserDao userDao;@Overridepublic boolean save(User user) {return userDao.save(user);}@Overridepublic boolean update(User user) {return userDao.update(user);}@Overridepublic boolean delete(Integer uuid) {return userDao.delete(uuid);}@Overridepublic User get(Integer uuid) {return userDao.get(uuid);}//分页查询@Overridepublic PageInfo<User> getAll(int page,int size) {PageHelper.startPage(page,size);List<User> all = userDao.getAll();return new PageInfo<User>(all);}@Overridepublic User login(String userName, String password) {return userDao.getByUserNameAndPassword(userName, password);}
}
package com.zs.service;import com.github.pagehelper.PageInfo;
import com.zs.domain.User;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@Transactional(readOnly = true)
public interface UserService {@Transactional(readOnly = false)boolean save(User user);@Transactional(readOnly = false)boolean update(User user);@Transactional(readOnly = false)boolean delete(Integer uuid);User get(Integer uuid);PageInfo<User> getAll(int page, int size);User login(String userName,String password);
}

整合SpringMVC

  • web.xml加载SpringMVC
  • rest风格
  • 数据封装为json数据
<?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_2_5.xsd"version="2.5"><!--加载spring容器--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><filter><filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><servlet><servlet-name>DispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath*:spring-mvc.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>DispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/mvchttps://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scan base-package="com.zs.controller"/><mvc:annotation-driven/>
</beans>

userController

package com.zs.controller;import com.zs.domain.User;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/user")
public class UserController {/*** 新增* @param user* @return*/@PostMappingpublic boolean save(User user){System.out.println("save ..." + user);return true;}/*** 修改* @param user* @return*/@PutMappingpublic boolean update(User user){System.out.println("update ..." + user);return true;}/*** 删除* @param uuid* @return*/@DeleteMapping("/{uuid}")public boolean delete(@PathVariable Integer uuid){System.out.println("delete ..." + uuid);return true;}@GetMapping("/{uuid}")public User get(@PathVariable Integer uuid){System.out.println("get ..." + uuid);return null;}/*** 分页查* @param page* @param size* @return*/@GetMapping("/{page}/{size}")public List getAll(@PathVariable Integer page, @PathVariable Integer size){System.out.println("getAll ..." + page+","+size);return null;}/*** 登录* @param userName* @param password* @return*/@PostMapping("/login")public User login(String userName,String password){System.out.println("login ..." + userName + " ," +password);return null;}}
 <!--加载spring容器--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
package com.zs.controller;import com.github.pagehelper.PageInfo;
import com.zs.domain.User;
import com.zs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PostMappingpublic boolean save(User user){return userService.save(user);}@PutMappingpublic boolean update(User user){return userService.update(user);}@DeleteMapping("/{uuid}")public boolean delete(@PathVariable Integer uuid){return userService.delete(uuid);}@GetMapping("/{uuid}")public User get(@PathVariable Integer uuid){return userService.get(uuid);}@GetMapping("/{page}/{size}")public PageInfo<User> getAll(@PathVariable Integer page, @PathVariable Integer size){return userService.getAll(page,size);}@PostMapping("/login")public User login(String userName,String password){return userService.login(userName,password);}}

数据封装(定义数据交换中间件)



Result

package com.zs.controller.results;import com.zs.domain.User;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
public class Result {//    操作结果编码private Integer code;//    操作数据结果private Object data;//    消息private String message;public Result(Integer code) {this.code = code;}public Result(Integer code, Object data) {this.code = code;this.data = data;}public Result(Integer code, String message) {this.code = code;this.message = message;}//
//    public Result(Integer code, Object data) {//        this.code = code;
//        this.data = data;
//    }
//
//    @Override
//    public String toString() {//        return "Result{" +
//                "code=" + code +
//                ", data=" + data +
//                ", message='" + message + '\'' +
//                '}';
//    }
//
//    public Integer getCode() {//        return code;
//    }
//
//    public void setCode(Integer code) {//        this.code = code;
//    }
//
//    public Object getData() {//        return data;
//    }
//
//    public void setData(Object data) {//        this.data = data;
//    }
//
//    public String getMessage() {//        return message;
//    }
//
//    public void setMessage(String message) {//        this.message = message;
//    }
}

Code

package com.zs.controller.results;public class Code {//    操作结果编码public static final Integer SAVE_OK = 20011;public static final Integer UPDATE_OK = 20021;public static final Integer DELETE_OK = 20031;public static final Integer GET_OK = 20041;public static final Integer SAVE_ERROR = 20010;public static final Integer UPDATE_ERROR = 20020;public static final Integer DELETE_ERROR = 20030;public static final Integer GET_ERROR = 20040;//    系统错误编码//    操作权限编码//    校验结果编码}

统一异常处理

@Component
@ControllerAdvice
public class ProjectExceptionAdivce {@ExceptionHandler(BusinessException.class)@ResponseBody//对出现异常的情况进行拦截,并将其处理成统一的页面数据结果格式public Result doBusinessException(BusinessException e){return new Result(e.getCode(),e.getMessage());}}
package com.zs.system.exception;public class BusinessException extends RuntimeException {//自定义异常中封装对应的错误编码,用于异常处理时获取对应的操作编码private Integer code;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public BusinessException(Integer code) {this.code = code;}public BusinessException(String message, Integer code) {super(message);this.code = code;}public BusinessException(String message, Throwable cause,Integer code) {super(message, cause);this.code = code;}public BusinessException(Throwable cause,Integer code) {super(cause);this.code = code;}public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace,Integer code) {super(message, cause, enableSuppression, writableStackTrace);this.code = code;}
}
package com.zs.system.exception;public class SystemException extends RuntimeException {public SystemException() {}public SystemException(String message) {super(message);}public SystemException(String message, Throwable cause) {super(message, cause);}public SystemException(Throwable cause) {super(cause);}public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);}
}

表现层业务方法处理

package com.zs.controller;import com.github.pagehelper.PageInfo;
import com.zs.controller.results.Code;
import com.zs.controller.results.Result;
import com.zs.domain.User;
import com.zs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PostMappingpublic Result save(User user){boolean flag = userService.save(user);return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERROR);}@PutMappingpublic Result update(User user){boolean flag = userService.update(user);return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERROR);}@DeleteMapping("/{uuid}")public Result delete(@PathVariable Integer uuid){boolean flag = userService.delete(uuid);return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERROR);}@GetMapping("/{uuid}")public Result get(@PathVariable Integer uuid){User user = userService.get(uuid);return new Result(null != user ?Code.GET_OK: Code.GET_ERROR,user);}@GetMapping("/{page}/{size}")public Result getAll(@PathVariable Integer page, @PathVariable Integer size){PageInfo<User> all = userService.getAll(page, size);return new Result(null != all ?Code.GET_OK: Code.GET_ERROR,all);}@PostMapping("/login")public Result login(String userName,String password){User user = userService.login(userName,password);return new Result(null != user ?Code.GET_OK: Code.GET_ERROR,user);}}

注解整合

userDao.xml

public interface UserDao {/*** 添加用户* @param user* @return*/@Insert("insert into user(userName,password,realName,gender,birthday)values(#{userName},#{password},#{realName},#{gender},#{birthday})")public boolean save(User user);/*** 修改用户* @param user* @return*/@Update("update user set userName=#{userName},password=#{password},realName=#{realName},gender=#{gender},birthday=#{birthday} where uuid=#{uuid}")public boolean update(User user);/*** 删除用户* @param uuid* @return*/@Delete("delete from user where uuid = #{uuid}")public boolean delete(Integer uuid);/*** 查询单个用户信息* @param uuid* @return*/@Select("select * from user where uuid = #{uuid}")public User get(Integer uuid);/*** 查询全部用户信息* @return*/@Select("select * from user")public List<User> getAll();/*** 根据用户名密码查询个人信息* @param userName 用户名* @param password 密码信息* @return*/@Select("select * from user where userName=#{userName} and password=#{password}")//注意:数据层操作不要和业务层操作的名称混淆,通常数据层仅反映与数据库间的信息交换,不体现业务逻辑public User getByUserNameAndPassword(@Param("userName") String userName,@Param("password") String password);
}

web.xml

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {//创建Servlet容器时,使用注解的方式加载SPRINGMVC配置类中的信息,并加载成WEB专用的ApplicationContext对象//该对象放入了ServletContext范围,后期在整个WEB容器中可以随时获取调用@Overrideprotected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();ctx.register(SpringMvcConfig.class);return ctx;}//注解配置映射地址方式,服务于SpringMVC的核心控制器DispatcherServlet@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}@Override//基本等同于<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>protected WebApplicationContext createRootApplicationContext() {AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();ctx.register(SpringConfig.class);return ctx;}//乱码处理作为过滤器,在servlet容器启动时进行配置,相关内容参看Servlet零配置相关课程@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {//触发父类的onStartupsuper.onStartup(servletContext);//1.创建字符集过滤器对象CharacterEncodingFilter cef = new CharacterEncodingFilter();//2.设置使用的字符集cef.setEncoding("UTF-8");//3.添加到容器(它不是ioc容器,而是ServletContainer)FilterRegistration.Dynamic registration = servletContext.addFilter("characterEncodingFilter", cef);//4.添加映射registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), false, "/*");}
}

applicationContext.xml

SpringConfig

@Configuration
//等同于<context:component-scan base-package="com.itheima">
@ComponentScan(value = "com.itheima",excludeFilters =//等同于<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>@ComponentScan.Filter(type= FilterType.ANNOTATION,classes = {Controller.class}))
//等同于<context:property-placeholder location="classpath*:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties")
//等同于<tx:annotation-driven />,bean的名称默认取transactionManager
@EnableTransactionManagement
@Import({MyBatisConfig.class,JdbcConfig.class})
public class SpringConfig {//等同于<bean id="txManager"/>@Bean("transactionManager")//等同于<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">public DataSourceTransactionManager getTxManager(@Autowired DataSource dataSource){DataSourceTransactionManager tm = new DataSourceTransactionManager();//等同于<property name="dataSource" ref="dataSource"/>tm.setDataSource(dataSource);return tm;}
}

JdbcConfig

package com.itheima.config;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class JdbcConfig {//使用注入的形式,读取properties文件中的属性值,等同于<property name="*******" value="${jdbc.driver}"/>@Value("${jdbc.driver}")private String driver;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String userName;@Value("${jdbc.password}")private String password;//定义dataSource的bean,等同于<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">@Bean("dataSource")public DataSource getDataSource(){//创建对象DruidDataSource ds = new DruidDataSource();//手工调用set方法,等同于set属性注入<property name="driverClassName" value="******"/>ds.setDriverClassName(driver);ds.setUrl(url);ds.setUsername(userName);ds.setPassword(password);return ds;}
}

MyBatisConfig


public class MyBatisConfig {//定义MyBatis的核心连接工厂bean,等同于<bean class="org.mybatis.spring.SqlSessionFactoryBean">@Bean//参数使用自动装配的形式加载dataSource,为set注入提供数据,dataSource来源于JdbcConfig中的配置public SqlSessionFactoryBean getSqlSessionFactoryBean(@Autowired DataSource dataSource,@Autowired Interceptor interceptor){SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();//等同于<property name="typeAliasesPackage" value="com.itheima.domain"/>ssfb.setTypeAliasesPackage("com.itheima.domain");//等同于<property name="dataSource" ref="dataSource"/>ssfb.setDataSource(dataSource);
//        //等同于<bean class="com.github.pagehelper.PageInterceptor">
//        Interceptor interceptor = new PageInterceptor();
//        Properties properties = new Properties();
//        properties.setProperty("helperDialect","mysql");
//        properties.setProperty("reasonable","true");
//        //等同于<property name="properties">
//        interceptor.setProperties(properties);ssfb.setPlugins(interceptor);return ssfb;}//定义MyBatis的映射扫描,等同于<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">@Beanpublic MapperScannerConfigurer getMapperScannerConfigurer(){MapperScannerConfigurer msc = new MapperScannerConfigurer();//等同于<property name="basePackage" value="com.itheima.dao"/>msc.setBasePackage("com.itheima.dao");return msc;}@Bean("pageInterceptor")public Interceptor getPageInterceptor(){Interceptor interceptor = new PageInterceptor();Properties properties = new Properties();properties.setProperty("helperDialect","mysql");properties.setProperty("reasonable","true");//等同于<property name="properties">interceptor.setProperties(properties);return interceptor;}}

spring -mvc.xml

@Configuration
//等同于<context:component-scan base-package="com.itheima.controller"/>
@ComponentScan("com.itheima.controller")
//等同于<mvc:annotation-driven/>,还不完全相同
@EnableWebMvc
public class SpringMvcConfig {}

Spring ---- ssm整合相关推荐

  1. Spring SSM整合

    1 将applocationContext文件拆分:各干各的事(调用时使用:Spring*) 1   Spring-db.xml <?xml version="1.0" en ...

  2. SSM整合——Spring+SpringMVC+MyBatis整合

    文章目录 1. 数据库环境 2. 项目基本结构搭建 3. 配置MyBatis 4. 配置Spring 5. 配置SpringMVC 6. Controller和视图层编写 7. 配置Tomcat,进行 ...

  3. java框架ssm整合_SSM三大框架整合详细教程(Spring+SpringMVC+MyBatis)

    使用 SSM ( Spring . SpringMVC 和 Mybatis )已经有三个多月了,项目在技术上已经没有什么难点了,基于现有的技术就可以实现想要的功能,当然肯定有很多可以改进的地方.之前没 ...

  4. ssm如何支持热部署_最新Spring Boot实战文档推荐:项目搭建+配置+SSM整合

    在Spring Boot项目中,正常来说是不存在XML配置,这是因为Spring Boot不推荐使用XML,注意,排不支持,Spring Boot推荐开发者使用Java配置来搭建框架, Spring ...

  5. mybatis+spring+springmvc ssm整合

    文章目录 mybatis 开发我的第一个mybatis程序 关于mybatis的核心API:SqlSession对象. mybatis连接数据库操作 log4j jackson parameterTy ...

  6. ssm整合说明与模板-Spring Spring MVC Mybatis整合开发

    ssm整合说明 spring+spring mvc+mybatis 说明 源码下载 由于之前存在ssh框架,spring+struts+hibernate,其中spring负责aop与ioc,所以一般 ...

  7. 基于Maven+SpringMVC+Spring+MyBatis+Layui整合框架,超详细的SSM整合❤️

    人生有太多不如意,我们要学会去努力 参考文档:layUI文档:spring家族文档:mybatis文档 前言:SSM 整合 整合的思路是: 先创建spring框架 通过spring整合spring m ...

  8. SSM Chapter 07 MyBatis与Spring的整合

    SSM Chapter 07 MyBatis 与 Spring 的整合 笔记 本章目标: 掌握Spring与MyBatis的集成 掌握使用SqlSessionTemplate实现整合 掌握使用Mapp ...

  9. 超级详细!!!Spring、SpringMVC、Mybatis知识点完整版更新!IOD、DI依赖注入、Mybatis配置、SQL、MVC拦截器、Web开发、SSM整合案例。

    Spring Spring框架知识点完整版 上篇,SSM三部曲之一 知识点涵盖:Spring简介IOC控制反转DI依赖注入LombokSPEL配置文件低频知识点注解开发Spring常用注解 链接:ht ...

最新文章

  1. TCP/IP 广播的发送和接收
  2. HBase在淘宝的应用和优化小结
  3. 前端学习(482):html之b/s和c/s
  4. 信息学奥赛一本通(1250:The Castle)
  5. float right不生效_【工具篇】程序员不愿意写 PPT 是姿势不对?
  6. 有谁了解 最基础的计算机的网络结构呢?
  7. 12.12 带触发器按钮的输入框
  8. React-Native 之 GD (三)近半小时热门
  9. Django admin组件源码流程
  10. 网络-无线中继(HG255d挂载8187)
  11. 从编写c语言源程序到运行,c语言 源代码到可执行程序的过程
  12. python实现英雄联盟信息获取
  13. 学编程c语言高考能加分吗,编程已列入中高考,孩子升学加分的机会你抓住了么?...
  14. N-S图、PAD图(例题)
  15. 10台世界上最快的超级计算机
  16. asp.net获取URL和IP地址(转)
  17. 消费者物价指数CPI
  18. 在H5中使用qrcode, qrcodejs2生成二维码
  19. vuex原理解析并实现一个简单的vuex
  20. Linux命令之diff命令

热门文章

  1. 离开小厂进大厂的第一周:我“后悔”了
  2. 业界分享 | 百度图神经网络实践
  3. 关于深度学习框架的一些见解
  4. Java实现非对称加密算法-RSA加解密
  5. 使用Sonar管理代码质量(一)–简述与安装
  6. 微信小程序如何零成本获客
  7. centos6.9负载均衡方案完整配置(lvs+keepalived+pxc+nfs+业务系统)
  8. 量子计算机张庆瑞讲座报告,燕山大学彭秋明、张庆瑞教授来我校开展学术交流...
  9. 开启Nginx压缩,解决前端访问慢问题
  10. Windows系统中使用SSH服务端和客户端