四、SSM三大框架整合之登錄功能實現


1、整合思路

  

 

  ①、表現層,也就是 Controller,由 SpringMVC 來控制,而SpringMVC 是Spring 的一個模塊,故不需要整合。

  ②、業務層,也就是 service,通常由 Spring 來管理 service 接口,我們會使用 xml 配置的方式來將 service 接口配置到 spring 配置文件中。而且事務控制一般也是在 service 層進行配置。

  ③、持久層,也就是 dao 層,而且包括實體類,由 MyBatis 來管理,通過 spring 來管理 mapper 接口,使用mapper的掃描器自動掃描mapper接口在spring中進行注冊。

  很明顯,spring 在三大框架的整合中占據至關重要的地位,類似於一個大管家,將 MyBatis 和 SpringMVC 揉合在一起。

 

 

2、准備環境

  ①、數據庫環境

    數據庫類型:MySQL 5.1

    數據庫名稱:ssm

    數據表:user

    

 

  ②、開發工具 eclipse

  ③、JDK 1.7

  ④、mybatis 3.3

  ⑤、SpringMVC 4.2.4

  ⑥、Spring 4.2.4

  ⑦、數據庫連接池 dbcp1.2.2

  ⑧、數據庫驅動包mysql5.1.26

  ⑨、日志 log4j 1.2

 

  案例需求:輸入用戶名和密碼進行登錄驗證

  具體的 jar 下載見上面的源碼下載鏈接!

   項目的目錄結構為:

  

 

 3、整合 Dao 層

   也就是整合 MyBatis 和 Spring

  ①、在 db.properties 文件中,保存數據庫連接的基本信息

1
2
3
4
5
6
#db.properties
dataSource=org.apache.commons.dbcp.BasicDataSource
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssm
username=root
password=root

  分別是數據庫連接池數據源,數據庫連接驅動,數據庫連接URL,數據庫連接用戶名,數據庫連接密碼

  ②、mybatis全局配置文件 mybatis-configuration.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<? 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 >
     <!-- 全局 setting 配置,根據需要添加  -->
     <!--開啟二級緩存  -->
     < settings >
         < setting  name="cacheEnabled" value="true"/>
     </ settings >
     
     <!-- 配置別名 -->
     < typeAliases >
         <!-- 批量掃描別名 -->
         < package  name="com.ys.po"/>
     </ typeAliases >
     
     <!-- 配置mapper,由於使用 spring 和mybatis 的整合包進行 mapper 掃描,這里不需要配置了
         必須遵循:mapper.xml 和 mapper.java 文件同名且在同一個目錄下
      -->
      <!-- <mappers>
      </mappers> -->
     
</ configuration >

  通過 mapper 接口來加載映射文件,具體可以看這篇博客:http://www.cnblogs.com/ysocean/p/7301548.html,必須滿足下面四點:

  1、xxxMapper 接口必須要和 xxxMapper.xml 文件同名且在同一個包下,也就是說 UserMapper.xml 文件中的namespace是UserMapper接口的全類名

  2、xxxMapper接口中的方法名和 xxxMapper.xml 文件中定義的 id 一致

  3、xxxMapper接口輸入參數類型要和 xxxMapper.xml 中定義的 parameterType 一致

  4、xxxMapper接口返回數據類型要和 xxxMapper.xml 中定義的 resultType 一致 

 

  ③、配置 Spring 文件

   我們需要配置數據源、SqlSessionFactory以及mapper掃描器,由於這是對 Dao 層的整合,后面還有對於 業務層,表現層等的整合,為了使條目更加清新,我們新建 config/spring 文件夾,這里將配置文件取名為 spring-dao.xml 放入其中。

  spring-dao.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<? 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"
   xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-3.2.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
 
     <!--第一步: 配置數據源 -->
     <!-- 加載db.properties文件中的內容,db.properties文件中的key名要有一定的特殊性 -->
     < context:property-placeholder  location="classpath:db.properties" />
     < bean  id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
         < property  name="driverClassName" value="${jdbc.driver}"></ property >
         < property  name="url" value="${jdbc.url}"></ property >
         < property  name="username" value="${jdbc.username}"></ property >
         < property  name="password" value="${jdbc.password}"></ property >
         < property  name="maxActive" value="30"></ property >
         < property  name="maxIdle" value="5"></ property >
     </ bean >
     
     <!-- 第二步:創建sqlSessionFactory。生產sqlSession  -->
     < bean  id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
         <!-- 數據庫連接池 -->
         < property  name="dataSource" ref="dataSource"></ property >
         <!-- 加載mybatis全局配置文件,注意這個文件的目錄 -->
         < property  name="configLocation" value="classpath:mybatis/mybatis-configuration.xml"></ property >
     </ bean >
     
     <!-- 第三步:配置 mapper 掃描器
         * 接口類名和映射文件必須同名
         * 接口類和映射文件必須在同一個目錄下
         * 映射文件namespace名字必須是接口的全類路徑名
         * 接口的方法名必須和映射Statement的id一致
     -->
     < bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         <!-- 掃描的包路徑,如果需要掃描多個包,中間使用逗號分隔 -->
         < property  name="basePackage" value="com.ys.mapper"></ property >
         < property  name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></ property >
     </ bean >
     
</ beans >

  ④、根據逆向工程生成 po 類以及 mapper 文件

  如何使用逆向工程,可以參考這篇博客:http://www.cnblogs.com/ysocean/p/7360409.html,我們逆向工程要是一個額外的工程,生成我們所需的po類以及mapper文件后,在將其復制到我們當前項目中,如下:

  

   由於我們這里是進行登錄驗證,所以在 UserMapper.java 中添加如下代碼:

1
2
3
4
5
6
7
8
9
10
11
12
package  com.ys.mapper;
 
import  com.ys.po.User;
import  java.util.List;
import  org.apache.ibatis.annotations.Param;
 
public  interface  UserMapper {
 
     //通過用戶名和密碼查詢User
     User selectUserByUsernameAndPassword(User user);
 
}

  UserMapper.xml 

1
2
3
4
<!-- 通過用戶名和密碼查詢User -->
   <select id= "selectUserByUsernameAndPassword"  resultType= "com.ys.po.User"  parameterType= "com.ys.po.User" >
     select * from user where username = #{username,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}
   </select>

  

 

   dao 層整合完畢之后,我們進行一個測試,要養成每做完一個小模塊必須測試的習慣。步步為營,如果整個項目配置完了然后在進行測試,那么有問題進行排除會變得很困難。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package  com.ys.test;
 
import  org.junit.Before;
import  org.junit.Test;
import  org.springframework.context.ApplicationContext;
import  org.springframework.context.support.ClassPathXmlApplicationContext;
 
import  com.ys.mapper.UserMapper;
import  com.ys.po.User;
 
 
public  class  DaoTest {
     ApplicationContext context =  null ;
     
     @Before
     public  void  init(){
         context =  new  ClassPathXmlApplicationContext( "classpath:spring/application-dao.xml" );
     }
     
     @Test
     public  void  testSelectByPrimaryKey(){
         UserMapper userMapper = (UserMapper) context.getBean( "userMapper" );
         User user = userMapper.selectByPrimaryKey( 1 );
         System.out.println(user.getPassword());
     }
     
}

  這里是根據 user 表的 id 進行查詢。如果能打印出user對象的值,那么前面的配置是 OK的。

 

 

4、整合 service

  前面我們整理了,這層就是用 Spring 來管理 service 接口,我們會使用 xml 配置的方式來將 service 接口配置到 spring 配置文件中。而且事務控制也是在 service 層進行配置。

  這里我們以登錄

  ①、定義 service 接口

1
2
3
4
5
6
7
8
9
10
package  com.ys.service.impl;
 
import  com.ys.po.User;
 
public  interface  IUserService {
     
     //通過用戶名和密碼查詢User
     public  User selectUserByUsernameAndPassword(User user);
 
}

  ②、編寫 service 實現類

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package  com.ys.service;
 
import  org.springframework.beans.factory.annotation.Autowired;
 
import  com.ys.mapper.UserMapper;
import  com.ys.po.User;
import  com.ys.service.impl.IUserService;
 
public  class  UserServiceImpl  implements  IUserService{
 
     @Autowired
     private  UserMapper userMapper;  //通過@Autowired向spring容器注入UserMapper
     
     //通過用戶名和密碼查詢User
     @Override
     public  User selectUserByUsernameAndPassword(User user) {
         User u = userMapper.selectUserByUsernameAndPassword(user);
         return  u;
     }
 
}

  通過@Autowired向spring容器注入UserMapper,它會通過spring配的掃描器掃描到,並將對象裝載到spring容器中。

  

  ③、在spring容器中配置 Service 接口,這里我們使用 xml 的方式

  在 config/spring 目錄下,新建 spring-service.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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"
   xmlns:aop= "http://www.springframework.org/schema/aop"  xmlns:tx= "http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http: //www.springframework.org/schema/beans
     http: //www.springframework.org/schema/beans/spring-beans-3.2.xsd
     http: //www.springframework.org/schema/mvc
     http: //www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
     http: //www.springframework.org/schema/context
     http: //www.springframework.org/schema/context/spring-context-3.2.xsd
     http: //www.springframework.org/schema/aop
     http: //www.springframework.org/schema/aop/spring-aop-3.2.xsd
     http: //www.springframework.org/schema/tx
     http: //www.springframework.org/schema/tx/spring-tx-3.2.xsd">
 
     <!--配置UserServiceImpl -->
     <bean id= "userService"  class = "com.ys.service.UserServiceImpl" ></bean>
     
</beans>

  

  

  ④、在spring容器中配置 事務處理

  在 config/spring 目錄下,新建 spring-transaction.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?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"
   xmlns:aop= "http://www.springframework.org/schema/aop"  xmlns:tx= "http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http: //www.springframework.org/schema/beans
     http: //www.springframework.org/schema/beans/spring-beans-3.2.xsd
     http: //www.springframework.org/schema/mvc
     http: //www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
     http: //www.springframework.org/schema/context
     http: //www.springframework.org/schema/context/spring-context-3.2.xsd
     http: //www.springframework.org/schema/aop
     http: //www.springframework.org/schema/aop/spring-aop-3.2.xsd
     http: //www.springframework.org/schema/tx
     http: //www.springframework.org/schema/tx/spring-tx-3.2.xsd">
 
     <!-- 事務管理器 -->
     <!-- 對mybatis操作數據事務控制,spring使用jdbc的事務控制類 -->
     <bean id= "transactionManager"  class = "org.springframework.jdbc.datasource.DataSourceTransactionManager" >
          <!-- 數據源dataSource在spring-dao.xml中配置了 -->
          <property name= "dataSource"  ref= "dataSource" />
     </bean>
 
     <!-- 通知 -->
     <tx:advice id= "txAdvice"  transaction-manager= "transactionManager" >
          <tx:attributes>
              <tx:method name= "save*"  propagation= "REQUIRED" />
              <tx:method name= "delete*"  propagation= "REQUIRED" />
              <tx:method name= "update*"  propagation= "REQUIRED" />
              <tx:method name= "insert*"  propagation= "REQUIRED" />
              <tx:method name= "find*"  propagation= "SUPPORTS"  read-only= "true" />
              <tx:method name= "get*"  propagation= "SUPPORTS"  read-only= "true" />
              <tx:method name= "select*"  propagation= "SUPPORTS"  read-only= "true" />
          </tx:attributes>
     </tx:advice>
     
     <aop:config>
          <!-- com.ys.service.impl包里面的所有類,所有方法,任何參數 -->
          <aop:advisor advice-ref= "txAdvice"  pointcut= "execution(* com.ys.service.impl.*.*(..))" />
     </aop:config>    
</beans>

 

 

4、整合 SpringMVC

  ①、配置前端控制器

  在 web.xml 文件中添加如下代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
   <display-name>SpringMVC_01</display-name>
   <!-- 配置前端控制器DispatcherServlet -->
   <servlet>
     <servlet-name>springmvc</servlet-name>
     <servlet- class >org.springframework.web.servlet.DispatcherServlet</servlet- class >
     <!--springmvc.xml 是自己創建的SpringMVC全局配置文件,用contextConfigLocation作為參數名來加載
         如果不配置 contextConfigLocation,那么默認加載的是/WEB-INF/servlet名稱-servlet.xml,在這里也就是 springmvc-servlet.xml
       -->
     <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:spirng/springmvc.xml</param-value>
     </init-param>
   </servlet>
 
   <servlet-mapping>
     <servlet-name>springmvc</servlet-name>
     <!--第一種配置:*. do ,還可以寫*.action等等,表示以. do 結尾的或者以.action結尾的URL都由前端控制器DispatcherServlet來解析
         第二種配置:/,所有訪問的 URL 都由DispatcherServlet來解析,但是這里最好配置靜態文件不由DispatcherServlet來解析
         錯誤配置:/*,注意這里是不能這樣配置的,應為如果這樣寫,最后轉發到 jsp 頁面的時候,仍然會由DispatcherServlet進行解析,
                     而這時候會找不到對應的Handler,從而報錯!!!
       -->
     <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

  

  ②、配置處理器映射器、處理器適配器、視圖解析器

  在 config/spring 目錄下新建 springmvc.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?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"
        xmlns:aop= "http://www.springframework.org/schema/aop"
        xmlns:tx= "http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http: //www.springframework.org/schema/beans
         http: //www.springframework.org/schema/beans/spring-beans-4.2.xsd
         http: //www.springframework.org/schema/mvc
         http: //www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
         http: //www.springframework.org/schema/context
         http: //www.springframework.org/schema/context/spring-context.xsd
         http: //www.springframework.org/schema/aop
         http: //www.springframework.org/schema/aop/spring-aop-4.2.xsd
         http: //www.springframework.org/schema/tx
         http: //www.springframework.org/schema/tx/spring-tx.xsd">
 
     <!--使用mvc:annotation-driven可以代替上面的映射器和適配器
         這里面會默認加載很多參數綁定方法,比如json轉換解析器就默認加載,所以優先使用下面的配置
       -->
     <mvc:annotation-driven></mvc:annotation-driven>
 
     
     <!--批量配置Handler,指定掃描的包全稱  -->
     <context:component-scan base- package = "com.ys.controller" ></context:component-scan>
     
 
     <!--配置視圖解析器  -->
     <bean  class = "org.springframework.web.servlet.view.InternalResourceViewResolver" >
         
     </bean>
</beans>

  

  

  ③、編寫 Handler,也就是 Controller

  在 com.ys.controller 包下新建 UserController.java 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package  com.ys.controller;
 
import  org.springframework.beans.factory.annotation.Autowired;
import  org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.servlet.ModelAndView;
 
import  com.ys.po.User;
import  com.ys.service.impl.IUserService;
 
@Controller
public  class  UserController {
     @Autowired
     public  IUserService userService;
     
     @RequestMapping ( "/login" )
     public  ModelAndView login(User user){
         ModelAndView mv =  new  ModelAndView();
         User u = userService.selectUserByUsernameAndPassword(user);
         //根據用戶名和密碼查詢user,如果存在,則跳轉到 success.jsp 頁面
         if (u !=  null ){
             mv.addObject( "username" , u.getUsername());
             mv.addObject( "user" , u);
             mv.setViewName( "view/success.jsp" );
         } else {
             //如果不存在,則跳轉到 login.jsp頁面重新登錄
             return  new  ModelAndView( "redirect:/login.jsp" );
         }
         return  mv;
     }
 
}

  

  ④、加載 Spring 容器

  我們在 classpath/spring 目錄下新建了 spring-dao.xml,spring-service.xml,spring-transaction.xml 這些文件,里面有我們配置的 mapper,controller,service,那么如何將這些加載到 spring 容器中呢?

  在 web.xml 文件中添加如下代碼:

1
2
3
4
5
6
7
8
<!-- 加載spring容器 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/spring-*.xml</param-value>
</context-param>
<listener>
    <listener- class >org.springframework.web.context.ContextLoaderListener</listener- class >
</listener>

  由於配置文件比較多,我們使用通配符加載的方式。注意:這段代碼最好要加在前端控制器的前面。

  至此 SSM 三大框架整合就完成了,接下來我們進行測試。

  

5、測試

  在 WebContent 目錄下創建 login.jsp 頁面,以及 success.jsp頁面,如下圖:

  

 

   login.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%@ page language= "java"  contentType= "text/html; charset=UTF-8"
     pageEncoding= "UTF-8" %>
<!DOCTYPE html PUBLIC  "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv= "Content-Type"  content= "text/html; charset=UTF-8" >
<title>Insert title here</title>
</head>
<body>
     <form action= "login"  method= "post" >
         <label>賬號:</label>
         <input type= "text"  id= "txtUsername"  name= "username"  placeholder= "請輸入賬號"  /><br/>
         <label>密碼:</label>
         <input type= "password"  id= "txtPassword"  name= "password"  placeholder= "請輸入密碼"  /><br/>
         <input type= "submit"  value= "提交"  />
         <input type= "reset"  value= "重置"  />
     </form>
</body>
</html>

  success.jsp

1
2
3
4
5
6
7
8
9
10
11
12
<%@ page language= "java"  contentType= "text/html; charset=UTF-8"
     pageEncoding= "UTF-8" %>
<!DOCTYPE html PUBLIC  "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<meta http-equiv= "Content-Type"  content= "text/html; charset=UTF-8" >
<title>Insert title here</title>
</head>
<body>
     Hello ${user.username}
</body>
</html>

  1、將項目發布到 tomcat,如何發布可以參考這篇博客:http://www.cnblogs.com/ysocean/p/6893446.html

  2、在瀏覽器輸入:http://localhost:8080/SSMDemo/login.jsp

  

  點擊提交:

   


免責聲明!

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



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