1. 程式人生 > >SSM框架搭建2(spring+springmvc+mybatis)

SSM框架搭建2(spring+springmvc+mybatis)

SSM框架搭建(spring+springmvc+mybatis)

置頂2018年01月23日 16:10:38閱讀數:55506  

 自己配置了一個SSM框架,打算做個小網站,這裡把SSM的配置流程詳細的寫了出來,方便很少接觸這個框架的朋友使用,文中各個資源均免費提供!(後續讀寫分離:https://blog.csdn.net/dwhdome/article/details/83380149

一.建立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.    
  7.   </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.   <!-- 載入配置檔案 -->
  13.   <context:property-placeholder location="classpath:*.properties" />
  14.   <!-- 資料庫連線池 -->
  15.   <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
  16.   destroy-method="close">
  17.   <property name="url" value="${jdbc.url}" />
  18.   <property name="username" value="${jdbc.username}" />
  19.   <property name="password" value="${jdbc.password}" />
  20.   <property name="driverClassName" value="${jdbc.driver}" />
  21.   <property name="maxActive" value="10" />
  22.   <property name="minIdle" value="5" />
  23.   </bean>
  24.   <!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
  25.   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  26.   <!-- 資料庫連線池 -->
  27.   <property name="dataSource" ref="dataSource" />
  28.   <!-- 載入mybatis的全域性配置檔案 -->
  29.   <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
  30.   </bean>
  31.   <!-- 自動掃描 將Mapper介面生成代理注入到Spring -->
  32.   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  33.   <property name="basePackage" value="com.mapper" />
  34.   </bean>
  35.   </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.    
  11.   <!-- spring自動去掃描base-pack下面或者子包下面的java檔案-->
  12.   <!--管理Service實現類-->
  13.   <context:component-scan base-package="com.service"/>
  14.   </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.    
  10.   <!-- 掃描controller -->
  11.   <context:component-scan base-package="com.controller" />
  12.    
  13.   <!-- Spring 來掃描指定包下的類,並註冊被@Component,@Controller,@Service,@Repository等註解標記的元件 -->
  14.   <mvc:annotation-driven />
  15.    
  16.   <!-- 配置SpringMVC的檢視解析器-->
  17.   <bean
  18.   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  19.   <property name="prefix" value="/WEB-INF/jsp/" />
  20.   <property name="suffix" value=".jsp" />
  21.   </bean>
  22.   </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)

log4j.rootLogger=error,CONSOLE,A
log4j.addivity.org.apache=false

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=error
log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} -%-4r [%t] %-5p  %x - %m%n
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.Encoding=gbk
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout


log4j.appender.A=org.apache.log4j.DailyRollingFileAppender  
log4j.appender.A.File=${catalina.home}/logs/FH_log/PurePro_
log4j.appender.A.DatePattern=yyyy-MM-dd'.log'
log4j.appender.A.layout=org.apache.log4j.PatternLayout  
log4j.appender.A.layout.ConversionPattern=[FH_sys]  %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L \: %m%n 

 (log4j.xml)

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <!-- Appenders --> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <param name="Target" value="System.out" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy HH:mm:ss} %-5p %c - %m%n" /> </layout> </appender> <!-- Application Loggers --> <logger name="com"> <level value="error" /> </logger> <!-- 3rdparty Loggers --> <logger name="org.springframework.core"> <level value="error" /> </logger> <logger name="org.springframework.beans"> <level value="error" /> </logger> <logger name="org.springframework.context"> <level value="error" /> </logger> <logger name="org.springframework.web"> <level value="error" /> </logger> <logger name="org.springframework.jdbc"> <level value="error" /> </logger> <logger name="org.mybatis.spring"> <level value="error" /> </logger> <logger name="java.sql"> <level value="error" /> </logger> <!-- Root Logger --> <root> <priority value="error" /> <appender-ref ref="console" /> </root> </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.    
  3.   import javax.annotation.Resource;
  4.   import javax.servlet.http.HttpServletRequest;
  5.   import org.springframework.stereotype.Controller;
  6.   import org.springframework.web.bind.annotation.RequestMapping;
  7.   import org.springframework.web.servlet.ModelAndView;
  8.   import com.pojo.User;
  9.   import com.service.UserService;
  10.    
  11.   @Controller
  12.   @RequestMapping("/user")
  13.   public class UserController {
  14.    
  15.   @Resource(name="userService")
  16.   private UserService userService;
  17.   /**
  18.   * 根據id查詢
  19.   */
  20.   @RequestMapping(value="/queryById")
  21.   public ModelAndView queryById(HttpServletRequest request){
  22.   ModelAndView mv = new ModelAndView();
  23.   String id = request.getParameter( "id");
  24.   try{
  25.   User var = userService.findById(id);
  26.   mv.setViewName( "index");
  27.   mv.addObject( "var", var);
  28.   } catch(Exception e){
  29.   e.printStackTrace();
  30.   }
  31.   return mv;
  32.   }
  33.   }

UserService.java

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

 

補上之前漏掉得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.