当前位置:   article > 正文

SSM整合-(spring+spring mvc+Mybatis)_ssm+mybatis+spring+springmvc

ssm+mybatis+spring+springmvc

目录

一、什么是SSM框架

二、系统架构图

三、搭建步骤

四、SSM框架示例

五、总结


介绍SSM框架<原理>
一、什么是SSM框架?
SSM框架是spring、spring MVC 、和mybatis框架的整合,是标准的MVC模式。SSM框架即是将SpringMVC框架、Spring框架、MyBatis框架整合使用。以简化在web开发中繁琐、重复的操作,让开发人员的精力专注于业务处理的开发上。标准的SSM框架有四层,分别是dao层(mapper),service层,controller层和View层。使用spring实现业务对象管理,使用spring MVC负责请求的转发和视图管理,mybatis作为数据对象的持久化引擎。

二、系统架构图

三、搭建步骤

SSM框架搭建实现步骤

(1)创建Web项目

创建项目包结构

引入相关jar文件

(2)修改web.xml文件

配置Spring MVC的前端控制器,指定Spring MVC配置文件位置(如下参考)

  1. <servlet>
  2. <servlet-name>springmvc</servlet-name>
  3. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  4. <init-param>
  5. <param-name>contextConfigLocation</param-name>
  6. <param-value>classpath:springmvc.xml</param-value>
  7. </init-param>
  8. <load-on-startup>1</load-on-startup>
  9. </servlet>
  10. <servlet-mapping>
  11. <servlet-name>springmvc</servlet-name>
  12. <url-pattern>/</url-pattern>
  13. </servlet-mapping>

配置Spring框架的ContextLoaderListener(如下参考)

  1. <context-param>
  2. <param-name>contextConfigLocation</param-name>
  3. <param-value>classpath:application.xml</param-value>
  4. </context-param>

配置字符编码过滤器(如下参考)

  1. <!--乱码过滤-->
  2. <filter>
  3. <filter-name>encodingFilter</filter-name>
  4. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  5. <init-param>
  6. <param-name>encoding</param-name>
  7. <param-value>utf-8</param-value>
  8. </init-param>
  9. </filter>
  10. <filter-mapping>
  11. <filter-name>encodingFilter</filter-name>
  12. <url-pattern>/*</url-pattern>
  13. </filter-mapping>

配置web.xml完整代码(如下参考)

  1. <!DOCTYPE web-app PUBLIC
  2. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3. "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  7. version="4.0">
  8. <description>Archetype Created Web Application</description>
  9. <context-param>
  10. <param-name>contextConfigLocation</param-name>
  11. <param-value>classpath:application.xml</param-value>
  12. </context-param>
  13. <filter>
  14. <filter-name>encodingFilter</filter-name>
  15. <filter-class>
  16. org.springframework.web.filter.CharacterEncodingFilter
  17. </filter-class>
  18. <init-param>
  19. <param-name>encoding</param-name>
  20. <param-value>UTF-8</param-value>
  21. </init-param>
  22. <init-param>
  23. <param-name>forceEncoding</param-name>
  24. <param-value>true</param-value>
  25. </init-param>
  26. </filter>
  27. <filter-mapping>
  28. <filter-name>encodingFilter</filter-name>
  29. <url-pattern>/*</url-pattern>
  30. </filter-mapping>
  31. <servlet>
  32. <servlet-name>springmvc</servlet-name>
  33. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  34. <init-param>
  35. <param-name>contextConfigLocation</param-name>
  36. <param-value>classpath:springmvc.xml</param-value>
  37. </init-param>
  38. <load-on-startup>1</load-on-startup>
  39. </servlet>
  40. <servlet-mapping>
  41. <servlet-name>springmvc</servlet-name>
  42. <url-pattern>/</url-pattern>
  43. </servlet-mapping>
  44. <listener>
  45. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  46. </listener>
  47. </web-app>

(3)编写配置文件

database.properties(如下参考)

  1. driver=com.mysql.cj.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/bian_li_dian?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT-8
  3. user=root
  4. pwd=123456

applicationContext-mybatis.xml(如下参考)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xmlns:context="http://www.springframework.org/schema/context"
  8. xsi:schemaLocation="
  9. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  10. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  11. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  12. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  13. " >
  14. <!-- 加载属性文件 -->
  15. <context:property-placeholder location="classpath:database.properties"></context:property-placeholder>
  16. <!-- 配置数据源 -->
  17. <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
  18. <property name="driverClassName" value="${driver}"></property>
  19. <property name="url" value="${url}"></property>
  20. <property name="username" value="${user}"></property>
  21. <property name="password" value="${pwd}"></property>
  22. </bean>
  23. <!-- 整合sqlSessionFactory -->
  24. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  25. <property name="dataSource" ref="dataSource"></property>
  26. <property name="configLocation" value="classpath:mybatis.xml"></property>
  27. <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
  28. </bean>
  29. <!-- 专门扫描mapper接口 -->
  30. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  31. <property name="basePackage" value="com.xinxi2.mapper"></property>
  32. </bean>
  33. <!-- 扫描@component的 -->
  34. <context:component-scan base-package="com.xinxi2"></context:component-scan>
  35. <!-- 数据源事务管理器 ioc,指定管理的数据源 -->
  36. <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
  37. <property name="dataSource" ref="dataSource"></property>
  38. </bean>
  39. <!-- 事务管理器增强,配置方法的事务传播机制 -->
  40. <tx:advice id="txAdvice" transaction-manager="txManager">
  41. <tx:attributes>
  42. <tx:method name="add*" propagation="REQUIRED"/>
  43. <tx:method name="update*" propagation="REQUIRED"/>
  44. <tx:method name="del*" propagation="REQUIRED"/>
  45. <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
  46. </tx:attributes>
  47. </tx:advice>
  48. <aop:config>
  49. <aop:pointcut id="servicePointcut" expression="execution(* com.xinxi2.service..*.*(..))"/>
  50. <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"></aop:advisor>
  51. </aop:config>
  52. </beans>

mybatis-config.xml(如下参考)

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!-- 全局设置 -->
  7. <settings>
  8. <setting name="logImpl" value="LOG4J"/>
  9. </settings>
  10. </configuration>

typeAliases

typeAliases是MyBatis中的别名处理器类,翻译过来就是别名的意思,自动扫描cn.com.hello.pojo下的类型(如下参考)

  1. <typeAliases>
  2. <package name="cn.com.hello.pojo"/>
  3. </typeAliases>

全局性懒加载

懒加载的目的是减少内存的浪费和减轻系统的负担

springmvc-servlet.xml(如下参考)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. https://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/mvc
  12. https://www.springframework.org/schema/mvc/spring-mvc.xsd
  13. ">
  14. <context:component-scan base-package="com.xinxi2.controller,com.xinxi2.service"></context:component-scan>
  15. <!--Ajax 从controller到视图-->
  16. <mvc:annotation-driven>
  17. <mvc:message-converters>
  18. <bean class="org.springframework.http.converter.StringHttpMessageConverter">
  19. <property name="supportedMediaTypes">
  20. <list>
  21. <value>application/json;charset=UTF-8</value>
  22. <value>text/html;charset=UTF-8</value>
  23. </list>
  24. </property>
  25. </bean>
  26. <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
  27. <property name="supportedMediaTypes">
  28. <list>
  29. <value>text/html;charset=UTF-8</value>
  30. <value>application/json</value>
  31. </list>
  32. </property>
  33. <property name="features">
  34. <list>
  35. <!-- Date的日期转换器 -->
  36. <value>WriteDateUseDateFormat</value>
  37. </list>
  38. </property>
  39. </bean>
  40. </mvc:message-converters>
  41. </mvc:annotation-driven>
  42. <!-- 配置多视图解析器 -->
  43. <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
  44. <!-- 是否启用参数支持,默认为true(支持),即xxx?format=json、xml等形式。 -->
  45. <property name="favorParameter" value="true" />
  46. <!-- favorPathExtension:是否支持扩展名,默认为true(支持),扩展名指xxx.json、xxx.xml等形式 -->
  47. <property name="favorPathExtension" value="true" />
  48. <!-- 默认ContentType -->
  49. <property name="defaultContentType" value="application/json" />
  50. <!-- 配置映射关系 -->
  51. <!--扩展名到MIME的映射;favorPathExtension, favorParameter是true时起作用 -->
  52. <property name= "mediaTypes">
  53. <value>
  54. json=application/json
  55. xml=application/xml
  56. html=text/html
  57. </value>
  58. </property>
  59. </bean>
  60. <!-- VIEW解析定义。内容协商视图解析器;根据contentNegotiationManager使用的不同mediaTypes决定不同的 view进行响应 默认使用json-->
  61. <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  62. <!-- 内容协商管理器 用于决定media type -->
  63. <property name="contentNegotiationManager" ref="contentNegotiationManager"/>
  64. <!-- 默认视图 解析 -->
  65. <property name="defaultViews">
  66. <list>
  67. <bean class="com.alibaba.fastjson.support.spring.FastJsonJsonView">
  68. <property name="charset" value="UTF-8"/>
  69. </bean>
  70. </list>
  71. </property>
  72. <property name="viewResolvers">
  73. <list>
  74. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  75. <property name="prefix" value="/WEB-INF/jsp/"/>
  76. <property name="suffix" value=""/>
  77. </bean>
  78. </list>
  79. </property>
  80. </bean>
  81. <!-- 一般视图解析器 -->
  82. <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
  83. <!-- <property name="prefix" value="/WEB-INF/jsp/"></property>-->
  84. <!-- <property name="suffix" value=""></property>-->
  85. <!-- </bean>-->
  86. <!-- 解决静态资源的加载问题 -->
  87. <mvc:resources mapping="/staticabc/**" location="/static/"></mvc:resources>
  88. <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  89. <property name="exceptionMappings">
  90. <props>
  91. <prop key="java.lang.RuntimeException">error.jsp</prop>
  92. </props>
  93. </property>
  94. </bean>
  95. <!-- 配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver -->
  96. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  97. <property name="maxUploadSize" value="5000000"/>
  98. <property name="defaultEncoding" value="UTF-8"/>
  99. </bean>
  100. <!-- <mvc:interceptors>-->
  101. <!-- <mvc:interceptor>-->
  102. <!-- <mvc:mapping path="/hello/**"/>-->
  103. <!-- <mvc:exclude-mapping path="/hello/hello04"/>-->
  104. <!-- <bean class="com.interceptor.LoginInterceptor"></bean>-->
  105. <!-- </mvc:interceptor>-->
  106. <!-- </mvc:interceptors>-->
  107. </beans>

log4j.properties(如下参考)

  1. log4j.rootLogger=DEBUG,CONSOLE,file
  2. #log4j.rootLogger=ERROR,ROLLING_FILE
  3. log4j.logger.cn.smbms.dao=debug
  4. log4j.logger.com.ibatis=debug
  5. log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
  6. log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
  7. log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
  8. log4j.logger.java.sql.Connection=debug
  9. log4j.logger.java.sql.Statement=debug
  10. log4j.logger.java.sql.PreparedStatement=debug
  11. log4j.logger.java.sql.ResultSet=debug
  12. log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
  13. ######################################################################################
  14. # Console Appender \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
  15. ######################################################################################
  16. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
  17. log4j.appender.Threshold=error
  18. log4j.appender.CONSOLE.Target=System.out
  19. log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
  20. log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
  21. ######################################################################################
  22. # DailyRolling File \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
  23. ######################################################################################
  24. log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
  25. log4j.appender.file.DatePattern=yyyy-MM-dd
  26. log4j.appender.file.File=log.log
  27. log4j.appender.file.Append=true
  28. log4j.appender.file.Threshold=error
  29. log4j.appender.file.layout=org.apache.log4j.PatternLayout
  30. log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
  31. log4j.logger.com.opensymphony.xwork2=error

(4)创建详细包结构

四、SSM框架示例

以下是一个简单的SSM框架代码示例,包括了Spring、SpringMVC和MyBatis的集成:

  1. Spring配置文件(spring-context.xml)
  1. <!-- 数据库连接配置 -->
  2. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  3. <property name="driverClassName" value="${jdbc.driver}" />
  4. <property name="url" value="${jdbc.url}" />
  5. <property name="username" value="${jdbc.username}" />
  6. <property name="password" value="${jdbc.password}" />
  7. </bean>
  8. <!-- MyBatis配置 -->
  9. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  10. <property name="dataSource" ref="dataSource" />
  11. <property name="mapperLocations" value="classpath*:mapper/*.xml" />
  12. </bean>
  13. <!-- 扫描Mapper接口 -->
  14. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  15. <property name="basePackage" value="com.example.mapper" />
  16. </bean>
  17. <!-- Service组件扫描 -->
  18. <context:component-scan base-package="com.example.service" />
  19. <!-- 配置事务管理器 -->
  20. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  21. <property name="dataSource" ref="dataSource" />
  22. </bean>
  23. <!-- 启用事务管理 -->
  24. <tx:annotation-driven transaction-manager="transactionManager" />
  25. <!-- 加载外部属性文件 -->
  26. <context:property-placeholder location="classpath:jdbc.properties" />
  1. SpringMVC配置文件(spring-mvc.xml)
  1. <!-- 开启SpringMVC注解处理器 -->
  2. <mvc:annotation-driven />
  3. <!-- 静态资源映射 -->
  4. <mvc:resources mapping="/resources/**" location="/resources/" />
  5. <!-- 设置视图解析器 -->
  6. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  7. <property name="prefix" value="/WEB-INF/views/" />
  8. <property name="suffix" value=".jsp" />
  9. </bean>
  10. <!-- Controller组件扫描 -->
  11. <context:component-scan base-package="com.example.controller" />
  1. MyBatis Mapper接口示例(UserMapper.java)
  1. @Repository
  2. public interface UserMapper {
  3. @Select("SELECT * FROM users WHERE id = #{id}")
  4. User getUserById(Long id);
  5. @Insert("INSERT INTO users(username, password) VALUES(#{username}, #{password})")
  6. @Options(useGeneratedKeys = true, keyProperty = "id")
  7. int insertUser(User user);
  8. }
  1. Spring Service组件示例(UserService.java)
  1. @Service
  2. @Transactional
  3. public class UserService {
  4. @Autowired
  5. private UserMapper userMapper;
  6. public User getUserById(Long id) {
  7. return userMapper.getUserById(id);
  8. }
  9. public int insertUser(User user) {
  10. return userMapper.insertUser(user);
  11. }
  12. }
  1. SpringMVC Controller示例(UserController.java)
  1. @Controller
  2. @RequestMapping("/user")
  3. public class UserController {
  4. @Autowired
  5. private UserService userService;
  6. @RequestMapping("/{id}")
  7. public String getUserById(@PathVariable("id") Long id, Model model) {
  8. User user = userService.getUserById(id);
  9. model.addAttribute("user", user);
  10. return "user";
  11. }
  12. @RequestMapping(value = "/add", method = RequestMethod.POST)
  13. public String addUser(@ModelAttribute("user") User user) {
  14. userService.insertUser(user);
  15. return "redirect:/user/" + user.getId();
  16. }
  17. }

五、总结

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/907106
推荐阅读
相关标签
  

闽ICP备14008679号