SSM 框架-05-詳細整合教程(Eclipse版)(Spring+SpringMVC+MyBatis)


SSM 框架-05-詳細整合教程(Eclipse版)(Spring+SpringMVC+MyBatis)

如果你使用的是 Intellij IDEA,請查看:
SSM的配置流程詳細的寫了出來,方便很少接觸這個框架的朋友使用,文中各個資源均免費提供!

一.創建web項目(eclipse)

 File-->new-->Dynamic Web Project (這里我們創建的項目名為SSM)

下面是大致目錄結構

 

 

 

二. SSM所需jar包。

 

 jar包鏈接:https://pan.baidu.com/s/1dTClhO 密碼:n4mm

 

三.整合開始

 

1.mybatis配置文件(resource/mybatis/SqlMapConfig.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. </configuration>

2.Dao,mybatis整合spring,通過spring管理

SqlSessionFactory、mapper代理對象

(resource/spring/applicationContext-dao.xml)

 


  
  
  
          
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context= "http://www.springframework.org/schema/context" xmlns:p= "http://www.springframework.org/schema/p"
  4. xmlns:aop= "http://www.springframework.org/schema/aop" xmlns:tx= "http://www.springframework.org/schema/tx"
  5. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  9. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
  10. <!-- 數據庫連接池 -->
  11. <!-- 加載配置文件 -->
  12. <context:property-placeholder location="classpath:*.properties" />
  13. <!-- 數據庫連接池 -->
  14. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
  15. destroy-method= "close">
  16. <property name="url" value="${jdbc.url}" />
  17. <property name="username" value="${jdbc.username}" />
  18. <property name="password" value="${jdbc.password}" />
  19. <property name="driverClassName" value="${jdbc.driver}" />
  20. <property name="maxActive" value="10" />
  21. <property name="minIdle" value="5" />
  22. </bean>
  23. <!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
  24. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  25. <!-- 數據庫連接池 -->
  26. <property name="dataSource" ref="dataSource" />
  27. <!-- 加載mybatis的全局配置文件 -->
  28. <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
  29. </bean>
  30. <!-- 自動掃描 將Mapper接口生成代理注入到Spring -->
  31. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  32. <property name="basePackage" value="com.mapper" />
  33. </bean>
  34. </beans>

 

這里用的是阿里的連接池,當然也可以用c3p0,個人建議用阿里

 

3. 所有的實現類都放到spring容器中管理。由spring創建數據庫連接池,並有spring管理實務。

(resource/spring/applicationContext-service.xml)


  
  
  
          
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context= "http://www.springframework.org/schema/context" xmlns:p= "http://www.springframework.org/schema/p"
  4. xmlns:aop= "http://www.springframework.org/schema/aop" xmlns:tx= "http://www.springframework.org/schema/tx"
  5. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  9. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
  10. <!-- spring自動去掃描base-pack下面或者子包下面的java文件-->
  11. <!--管理Service實現類-->
  12. <context:component-scan base-package="com.service"/>
  13. </beans>

配置spring管理實務

 (resource/spring/applicationContext-trans.xml)


  
  
  
          
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context= "http://www.springframework.org/schema/context" xmlns:p= "http://www.springframework.org/schema/p"
  4. xmlns:aop= "http://www.springframework.org/schema/aop" xmlns:tx= "http://www.springframework.org/schema/tx"
  5. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  9. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
  10. <!-- 事務管理器 -->
  11. <bean id="transactionManager"
  12. class= "org.springframework.jdbc.datasource.DataSourceTransactionManager">
  13. <!-- 數據源 -->
  14. <property name="dataSource" ref="dataSource" />
  15. </bean>
  16. <!-- 通知 -->
  17. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  18. <tx:attributes>
  19. <!-- 傳播行為 -->
  20. <tx:method name="save*" propagation="REQUIRED" />
  21. <tx:method name="insert*" propagation="REQUIRED" />
  22. <tx:method name="add*" propagation="REQUIRED" />
  23. <tx:method name="create*" propagation="REQUIRED" />
  24. <tx:method name="delete*" propagation="REQUIRED" />
  25. <tx:method name="update*" propagation="REQUIRED" />
  26. <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
  27. <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
  28. <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
  29. </tx:attributes>
  30. </tx:advice>
  31. <!-- 切面 -->
  32. <aop:config>
  33. <aop:advisor advice-ref="txAdvice"
  34. pointcut= "execution(* com.service.*.*(..))" />
  35. </aop:config>
  36. </beans>

4. Springmvc整合spring框架,由springmvc管理controller

(resource/spring/springmvc.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" xmlns:p= "http://www.springframework.org/schema/p"
  4. xmlns:context= "http://www.springframework.org/schema/context"
  5. xmlns:mvc= "http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  9. <!-- 掃描controller -->
  10. <context:component-scan base-package="com.controller" />
  11. <!-- Spring 來掃描指定包下的類,並注冊被@Component,@Controller,@Service,@Repository等注解標記的組件 -->
  12. <mvc:annotation-driven />
  13. <!-- 配置SpringMVC的視圖解析器-->
  14. <bean
  15. class= "org.springframework.web.servlet.view.InternalResourceViewResolver">
  16. <property name="prefix" value="/WEB-INF/jsp/" />
  17. <property name="suffix" value=".jsp" />
  18. </bean>
  19. </beans>

5. 2中加載的屬性配置文件(dbconfig.properties)

根據自己的數據庫更改用戶名密碼以及庫


  
  
  
          
  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
  3. jdbc.username=root
  4. jdbc.password=123456

 

6. 配置log4j

(log4j.properties)


  
  
  
          
  1. log4j.rootLogger=error,CONSOLE,A
  2. log4j.addivity.org.apache=false
  3. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
  4. log4j.appender.CONSOLE.Threshold=error
  5. log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} -%- 4r [%t] %- 5p %x - %m%n
  6. log4j.appender.CONSOLE.Target=System.out
  7. log4j.appender.CONSOLE.Encoding=gbk
  8. log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
  9. log4j.appender.A=org.apache.log4j.DailyRollingFileAppender
  10. log4j.appender.A.File=${catalina.home}/logs/FH_log/PurePro _
  11. log4j.appender.A.DatePattern=yyyy-MM-dd '.log'
  12. log4j.appender.A.layout=org.apache.log4j.PatternLayout
  13. log4j.appender.A.layout.ConversionPattern=[FH_sys] %d{yyyy-MM-dd HH\:mm\:ss} %5p %c {1}\:%L \: %m%n

 (log4j.xml)


  
  
  
          
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
  3. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  4. <!-- Appenders -->
  5. <appender name="console" class="org.apache.log4j.ConsoleAppender">
  6. <param name="Target" value="System.out" />
  7. <layout class="org.apache.log4j.PatternLayout">
  8. <param name="ConversionPattern" value="%d{yyyy HH:mm:ss} %-5p %c - %m%n" />
  9. </layout>
  10. </appender>
  11. <!-- Application Loggers -->
  12. <logger name="com">
  13. <level value="error" />
  14. </logger>
  15. <!-- 3rdparty Loggers -->
  16. <logger name="org.springframework.core">
  17. <level value="error" />
  18. </logger>
  19. <logger name="org.springframework.beans">
  20. <level value="error" />
  21. </logger>
  22. <logger name="org.springframework.context">
  23. <level value="error" />
  24. </logger>
  25. <logger name="org.springframework.web">
  26. <level value="error" />
  27. </logger>
  28. <logger name="org.springframework.jdbc">
  29. <level value="error" />
  30. </logger>
  31. <logger name="org.mybatis.spring">
  32. <level value="error" />
  33. </logger>
  34. <logger name="java.sql">
  35. <level value="error" />
  36. </logger>
  37. <!-- Root Logger -->
  38. <root>
  39. <priority value="error" />
  40. <appender-ref ref="console" />
  41. </root>
  42. </log4j:configuration>

 SSM框架整合完成,至於mybatis逆向工程生成的mapper.xml和pojo請放到第一張圖的目錄下

注:逆向工程是根據數據庫表反向生成pojo以及mapper.xml,所以,請先自動在數據庫配置好user表。逆向工程得配置在下面得鏈接里面有詳細注釋。

測試數據庫表(User)

    private String id;

    private String username;

    private String password;

    private String company;

    private Integer age;

    private Integer sex;

根據類型創建表即可

 

逆向工程項目我會貼出鏈接,解壓導入改路徑運行main方法就會自動生成了,注意配置生成的路徑

 

逆向工程鏈接: 鏈接:https://pan.baidu.com/s/1QvSskH2UEC6EQF7MgVDOAQ 密碼:t2pc

到這里項目整合完成,接下來是測試!
 UserController.java


  
  
  
          
  1. package com.controller;
  2. import javax.annotation.Resource;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.servlet.ModelAndView;
  7. import com.pojo.User;
  8. import com.service.UserService;
  9. @Controller
  10. @RequestMapping( "/user")
  11. public class UserController {
  12. @Resource(name= "userService")
  13. private UserService userService;
  14. /**
  15. * 根據id查詢
  16. */
  17. @RequestMapping(value= "/queryById")
  18. public ModelAndView queryById(HttpServletRequest request){
  19. ModelAndView mv = new ModelAndView();
  20. String id = request.getParameter( "id");
  21. try{
  22. User var = userService.findById(id);
  23. mv.setViewName( "index");
  24. mv.addObject( "var", var);
  25. } catch(Exception e){
  26. e.printStackTrace();
  27. }
  28. return mv;
  29. }
  30. }

UserService.java


  
  
  
          
  1. package com.service;
  2. import javax.annotation.Resource;
  3. import org.springframework.stereotype.Service;
  4. import com.mapper.UserMapper;
  5. import com.pojo.User;
  6. @Service( "userService")
  7. public class UserService {
  8. @Resource
  9. private UserMapper dao;
  10. /*
  11. * 通過id獲取數據
  12. */
  13. public User findById(String id)throws Exception{
  14. return (User)dao.selectByPrimaryKey(id);
  15. }
  16. }

 

補上之前漏掉得web.xml配置


  
  
  
          
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns= "http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  4. xsi:schemaLocation= "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  5. id= "WebApp_ID" version= "2.5">
  6. <welcome-file-list>
  7. <welcome-file>index.jsp </welcome-file>
  8. </welcome-file-list>
  9. <!-- 加載spring容器 -->
  10. <context-param>
  11. <param-name>contextConfigLocation </param-name>
  12. <param-value>classpath:spring/applicationContext*.xml </param-value>
  13. </context-param>
  14. <listener>
  15. <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class>
  16. </listener>
  17. <!-- 解決post亂碼 -->
  18. <filter>
  19. <filter-name>CharacterEncodingFilter </filter-name>
  20. <filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class>
  21. <init-param>
  22. <param-name>encoding </param-name>
  23. <param-value>utf-8 </param-value>
  24. </init-param>
  25. <!-- <init-param>
  26. <param-name>forceEncoding</param-name>
  27. <param-value>true</param-value>
  28. </init-param> -->
  29. </filter>
  30. <filter-mapping>
  31. <filter-name>CharacterEncodingFilter </filter-name>
  32. <url-pattern>/* </url-pattern>
  33. </filter-mapping>
  34. <!-- springmvc的前端控制器 -->
  35. <!-- <servlet>
  36. <servlet-name>taotao-manager</servlet-name>
  37. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  38. contextConfigLocation不是必須的, 如果不配置contextConfigLocation, springmvc的配置文件默認在:WEB-INF/servlet的name+"-servlet.xml"
  39. <init-param>
  40. <param-name>contextConfigLocation</param-name>
  41. <param-value>classpath:spring/springmvc.xml</param-value>
  42. </init-param>
  43. <load-on-startup>1</load-on-startup>
  44. </servlet>
  45. <servlet-mapping>
  46. <servlet-name>SSM</servlet-name>
  47. <url-pattern>/</url-pattern>
  48. </servlet-mapping> -->
  49. <servlet>
  50. <servlet-name>springMvc </servlet-name>
  51. <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class>
  52. <init-param>
  53. <param-name>contextConfigLocation </param-name>
  54. <param-value>classpath:spring/springmvc.xml </param-value>
  55. </init-param>
  56. <load-on-startup>1 </load-on-startup>
  57. </servlet>
  58. <servlet-mapping>
  59. <servlet-name>springMvc </servlet-name>
  60. <url-pattern>/ </url-pattern>
  61. </servlet-mapping>
  62. </web-app>

 

為節省篇幅,更快的搭建成功,這里只寫了一個方法,根據id查詢數據

 

 

WebContent/index.jsp


  
  
  
          
  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding= "utf-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <%
  5. String path = request.getContextPath();
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  7. %>
  8. <html>
  9. <head>
  10. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  11. <title>查詢用戶 </title>
  12. </head>
  13. <body>
  14. <form action="user/queryById.do" method="post">
  15. 輸入要查詢的id: <input type="text" name="id" value="123456"/>
  16. <button type="submit">提交 </button>
  17. </form>
  18. </body>
  19. </html>

 WebContent/WEB-INF/jsp/index.jsp


  
  
  
          
  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding= "utf-8"%>
  3. <%@page import="com.pojo.*"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  8. <title>Insert title here </title>
  9. <style type="text/css">
  10. .td td{
  11. width: 100px;
  12. }
  13. .table{
  14. text-align: center;
  15. margin: 0 auto;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <%
  21. User user = ((User)request.getAttribute("var"));
  22. %>
  23. <table class="table">
  24. <tr class="td">
  25. <td>ID </td>
  26. <td>用戶名 </td>
  27. <td>密碼 </td>
  28. <td style="width: 200px">公司 </td>
  29. <td>年齡 </td>
  30. <td>性別 </td>
  31. </tr>
  32. <%if(user!=null){%>
  33. <tr class="td">
  34. <td> <%=user.getId()%> </td>
  35. <td> <%=user.getUsername()%> </td>
  36. <td> <%=user.getPassword()%> </td>
  37. <td> <%=user.getCompany()%> </td>
  38. <td> <%=user.getAge()%> </td>
  39. <td> <%=user.getSex()==1?"男":"女"%> </td>
  40. </tr>
  41. <%}else{ %>
  42. <tr class="td">
  43. <td style="color: red;">暫無相關數據 </td>
  44. </tr>
  45. <%} %>
  46. </table>
  47. </body>
  48. </html>

啟動項目,輸入localhost:8080/SSM 訪問

為方便新手查錯,博主按照博文重新搭建了一次,測試無誤后將項目打包,上傳至雲盤,供您使用。(建議:希望您按照博文從頭搭建,便於印象深刻)

 

項目完整鏈接(含數據庫): https://pan.baidu.com/s/17O8HgkoSYblFfC3uziMrdA 密碼:cw77

 

更多鏈接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM