SSM整合開發

Spring + Spring MVC + Mybatis 整合css

實現SSM的登陸、註冊功能。html

首先對SSM框架有一個總體意識前端

 

創建目錄結構:java

 

 

controller service mapper 三者關係:mysql

調用:controller --> service --> mappergit

返回:mapper --> service  --> controller github

controller:做爲請求轉發,調用service接口處理邏輯,頁面全部路徑的訪問方法:控制層的命名空間+@RequestMapping的value
service:接口,處理業務邏輯(impl裏面實現,調用mapper操做數據庫)
mapper:操做數據庫的接口web

 

第一,導入springspring mvcmybatis所須要的包ajax

 

第二,配置applicationContext.xmlspring

 1 <!-- 配置包掃描 -->
 2     <context:component-scan base-package="com.krry"></context:component-scan>
 3         
 4     <!-- 導入外部資源文件 -->
 5     <!-- <context:property-placeholder location="classpath:jdbc.properties" /> -->
 6     <bean class="com.krry.core.des.EncryptPropertyPlaceholderConfigurer"
 7  p:location="classpath:db/jdbc.properties" p:fileEncoding="utf-8" />
 8         
 9     <!-- proxool鏈接池 -->
10     <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">
11         <!-- 驅動的名字,mysql -->
12         <property name="driver" value="${db.driver}"></property>
13         <!--proxool 的 url鏈接串,這個必須肯定用戶名和密碼 -->
14         <property name="driverUrl" value="${db.url}"></property>
15         <!-- 用戶名(proxool沒有使用,可是不能沒有) -->
16         <property name="user" value="${db.username}"></property>
17         <!-- 密碼(proxool沒有使用,可是不能沒有) -->
18         <property name="password" value="${db.password}"></property>
19         <!-- proxool自動偵察各個鏈接狀態的時間間隔(毫秒),偵察到空閒的鏈接就立刻回收,超時的銷燬 如今設置爲4秒) -->
20         <property name="houseKeepingSleepTime" value="3000"></property><!-- 自動檢查鏈接是否斷掉開關 -->
21         <property name="testBeforeUse" value="true"></property>
22         <!-- 若是發現了空閒的數據庫鏈接.house keeper 將會用這個語句來測試.這個語句最好很是快的被執行.若是沒有定義,測試過程將會被忽略 -->
23         <property name="houseKeepingTestSql" value="SELECT count(1) from dual"></property>
24         <!-- 若是housekeeper 檢測到某個線程的活動時間大於這個數值.它將會殺掉這個線程.因此確認一下你的服務器的帶寬.而後定一個合適的值.默認是5分鐘. 如今設置 10 秒--> 
25         <property name="maximumActiveTime" value="10000"></property>
26         <!-- 最少保持的空閒鏈接數 (如今設置20個) -->
27         <property name="prototypeCount" value="20"></property>
28         <!-- 最大鏈接數 (如今設置100個) -->
29         <property name="maximumConnectionCount" value="200"></property>
30         <!-- 最小鏈接數 (如今設置50個) -->
31         <property name="minimumConnectionCount" value="50"></property>
32         <!-- 若是爲true,那麼每一個被執行的SQL語句將會在執行期被log記錄(DEBUG LEVEL).你也能夠註冊一個ConnectionListener (參看ProxoolFacade)獲得這些信息. -->
33         <property name="trace" value="false"></property>
34         <property name="verbose" value="true"></property>
35     </bean>
36     
37     <!-- 註冊事務管理器 -->
38     <bean id="txMgr"
39  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
40         <property name="dataSource" ref="dataSource"></property>
41     </bean>
42 
43     <!-- 開啓事務註解驅動 -->
44     <tx:annotation-driven transaction-manager="txMgr" />
45     
46     <!-- 配置mybatis的sqlSessionFactory -->
47     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
48         <property name="dataSource" ref="dataSource"></property>
49         <property name="configLocation" value="classpath:mybatis-config.xml"></property>
50     </bean>
51     
52     <!-- 配置能夠總體掃描Mapper的一個掃描器 -->
53     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
54         <!--若是有多個報路徑,用逗號分開便可 -->
55         <property name="basePackage" value="com.krry.mapper"></property>
56         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
57     </bean>

 

第三,配置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" 
 4  xmlns:p="http://www.springframework.org/schema/p"
 5  xmlns:context="http://www.springframework.org/schema/context"
 6  xmlns:util="http://www.springframework.org/schema/util" 
 7  xmlns:mvc="http://www.springframework.org/schema/mvc"
 8  xsi:schemaLocation="http://www.springframework.org/schema/beans  9  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  10  http://www.springframework.org/schema/context  11  http://www.springframework.org/schema/context/spring-context-3.0.xsd  12  http://www.springframework.org/schema/util  13  http://www.springframework.org/schema/util/spring-util-3.0.xsd  14  http://www.springframework.org/schema/mvc  15  http://www.springframework.org/schema/mvc/spring-mvc.xsd  16  ">
 17    
 18          <!-- 開啓註解模式驅動 -->    
 19         <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 
 20         <!-- 開啓mvc的註解模式 user 還會註冊一個ConversionService 子類FormattingConversionServiceFactoryBean-->
 21          <mvc:annotation-driven>
 22             <mvc:message-converters register-defaults="true">
 23                 <bean class="com.krry.core.UTF8StringHttpMessageConverter">
 24                     <property name="supportedMediaTypes">
 25                         <list>  
 26                             <value>text/plain;charset=UTF-8</value>  
 27                             <value>text/html;charset=UTF-8</value>  
 28                         </list>  
 29                     </property>
 30                 </bean> 
 31                 <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
 32                 <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> 
 33                 <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
 34                     <property name="prefixJson" value="false" />
 35                     <property name="objectMapper">
 36                          <bean class="com.fasterxml.jackson.databind.ObjectMapper">
 37                                <!-- 處理responseBody 裏面日期類型 --> 
 38                                <property name="dateFormat">  
 39                                    <bean class="java.text.SimpleDateFormat">  
 40                                        <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />  
 41                                    </bean>  
 42                                </property> 
 43                                <!-- 爲null字段時不顯示 -->
 44                                <property name="serializationInclusion">
 45                                    <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
 46                                </property> 
 47                            </bean>  
 48                     </property>
 49                      <property name="supportedMediaTypes">  
 50                         <list>  
 51                             <value>application/json;charset=UTF-8</value>  
 52                             <value>application/x-www-form-urlencoded;charset=UTF-8</value>  
 53                         </list>  
 54                     </property>
 55                 </bean>
 56                 </mvc:message-converters> 
 57         </mvc:annotation-driven>
 58         
 59          <!-- 掃包 -->
 60          <context:component-scan base-package="com.krry.controller"></context:component-scan>
 61          
 62          <!--對靜態資源文件的訪問 必需要設置,由於在springmvc的配置中配置了/匹配全部請求,  63  此工程全部的請求(.do ,addUser,js/image/css)都會被springmvc解析,  64  必須對全部的靜態資源文件進行過濾放行 -->
 65       <!-- 靜態資源過濾 下面二選一-->
 66       <!--<mvc:default-servlet-handler/> -->
 67       <mvc:resources mapping="/resourse/**" location="/resourse/" />
 68       
 69       <!-- 攔截器定義 -->
 70       <mvc:interceptors>    
 71           <mvc:interceptor>
 72              <!-- 我的中心也須要登錄 以admin開頭的配置都會進行攔截-->
 73                <mvc:mapping path="/admin/**"></mvc:mapping> 
 74                    <!-- 這個是設置不會進入攔截器的路徑 -->
 75                    <mvc:exclude-mapping path="/resourse/**"/>
 76             <!-- 攔截器進入的類,返回false表示不會進入輸入的路徑 -->
 77             <bean class="com.krry.core.filter.LoginInterceptor" />       
 78           </mvc:interceptor>
 79       </mvc:interceptors>
 80        
 81            <!-- 配置文件解析器 -->
 82         <bean id="multipartResolver"
 83  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
 84  p:defaultEncoding="utf-8">
 85             <property name="uploadTempDir" value="/temp"></property>
 86             <property name="maxUploadSize">
 87                 <value>209715200</value><!-- 200MB -->
 88             </property>
 89             <property name="maxInMemorySize">
 90                 <value>4096</value><!-- 4KB大小讀寫 -->
 91             </property>
 92         </bean>
 93            
 94    
 95        <!-- 視圖渲染 jsp/freemaker/velocity-->
 96        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 97                <!-- 制定頁面存放的路徑 -->
 98                <property name="prefix" value="/WEB-INF/pages/"></property>
 99                <!-- 文件的後綴 -->
100                <property name="suffix" value=".jsp"></property>
101        </bean> 
102     
103 </beans>

 

第四,配置mybatis-config.xml

 1 <configuration> 
 2     <settings>  
 3          <!-- 全局映射器啓用緩存 -->  
 4         <setting name="cacheEnabled" value="true" />  
 5          <!-- 查詢時,關閉關聯對象即時加載以提升性能 -->  
 6         <setting name="lazyLoadingEnabled" value="true" />  
 7         <!-- 設置關聯對象加載的形態,此處爲按需加載字段(加載字段由SQL指定),不會加載關聯表的全部字段,以提升性能 -->  
 8         <setting name="aggressiveLazyLoading" value="false" />  
 9         <!-- 對於未知的SQL查詢,容許返回不一樣的結果集以達到通用的效果 -->  
10         <setting name="multipleResultSetsEnabled" value="true" />  
11         <!-- 容許使用列標籤代替列名 -->  
12         <setting name="useColumnLabel" value="true" />  
13         <!-- 容許使用自定義的主鍵值(好比由程序生成的UUID 32位編碼做爲鍵值),數據表的PK生成策略將被覆蓋 -->  
14         <setting name="useGeneratedKeys" value="true" />  
15          <!-- 給予被嵌套的resultMap以字段-屬性的映射支持 -->  
16         <setting name="autoMappingBehavior" value="FULL" />  
17         <!-- 對於批量更新操做緩存SQL以提升性能 -->  
18         <setting name="defaultExecutorType" value="BATCH" />  
19          <!-- 數據庫超過25000秒仍未響應則超時 -->  
20         <setting name="defaultStatementTimeout" value="25" />  
21          <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
22     </settings>  
23     
24     <typeAliases>
25         <!--自定義user對象的別名 -->
26         <!-- <typeAlias type="com.krry.mybatis.sysmanage.entity.User" alias="user"/> -->
27         <!-- 批量定義別名 -->
28         <package name="com.krry.entity" />
29     </typeAliases>
30 
31     <!-- 配置pageHelper分頁插件 -->
32     <plugins>
33         <plugin interceptor="com.github.pagehelper.PageHelper">
34             <!-- 設置數據庫類型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數據庫 -->
35             <property name="dialect" value="mysql" />
36             <!--當設置爲true的時候,若是pagesize設置爲0 就不執行分頁,返回所有結果 -->
37             <property name="pageSizeZero" value="true" />
38             <!--合理化查詢 好比若是pageNum<1會查詢第一頁;若是pageNum>pages會查詢最後一頁(設置爲false返回空) -->
39             <property name="reasonable" value="false" />
40             <!-- 支持經過Mapper接口參數來傳遞分頁參數 -->
41             <property name="supportMethodsArguments" value="false" />
42             <!-- 老是返回PageInfo類型,check檢查返回類型是否爲PageInfo,none返回Page -->
43             <property name="returnPageInfo" value="none" />
44         </plugin>
45     </plugins>
46     
47     
48 </configuration>

在mybatis相應的xml文件配置mybatis的sql文件和mapper轉換器(也就是說的mapper下面的接口) 注入到sqlSessionFactory (放入到內存中)

1.  mapper的xml中,這裏的命名空間能夠隨便定義(必須惟一),可是爲了方便,定義成mapper包下的類的目錄,調用mapper下面類的接口方法的時候,調用的路徑是:mapper包下的類的目錄+方法名,便是與這個命名空間+id同樣,自動用了這個sql語句(id對應這個類的接口裏面的方法)這裏面一定有executeQuery方法,會執行這條sql語句。

2.  若是本身自定義名命名空間,調用下面的sql語句的方法爲:在mapper裏的方法執行如下語句:
SqlSession session = sessionFactory.openSession();
List<User> users = session.selectList("命名空間+id");   //根據實際結果集類型和sql語句類型,寫這條代碼就能夠獲取結果集

推薦使用第一種命名方式。

 mybatis執行流程:

 

 

第五,配置web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 3   
 4   <display-name>krry_SSM</display-name>
 5   
 6   <welcome-file-list>
 7     <welcome-file>index</welcome-file>
 8   </welcome-file-list>
 9   
10   <!-- 加載Spring IOC容器 -->
11   <context-param>
12     <param-name>contextConfigLocation</param-name>
13     <param-value>classpath:spring/applicationContext*.xml</param-value>
14   </context-param>
15   
16   <!-- spring上下文監聽器 -->
17   <listener>
18     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
19   </listener>
20   
21   <!-- Introspector緩存清除監聽器 -->
22   <listener>
23     <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
24   </listener>
25   
26   <filter>
27     <filter-name>encoding</filter-name>
28     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
29     <init-param>
30       <param-name>encoding</param-name>
31       <param-value>UTF-8</param-value>
32     </init-param>
33   </filter>
34   
35   <filter-mapping>
36     <filter-name>encoding</filter-name>
37     <url-pattern>/*</url-pattern>
38   </filter-mapping>
39   
40   <!-- 配置DispatcherServlet -->
41   <servlet>
42     <servlet-name>krry_SSM</servlet-name>
43     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
44     <!-- 配置springMVC的配置文件 -->
45     <!-- 若是不配置下面選項,系統默認加載classpath下面名爲[servlet-name]-servlet.xml的文件 springmvc01-servlet.xml -->
46     <init-param>
47       <param-name>contextConfigLocation</param-name>
48       <param-value>classpath:spring/springmvc.xml</param-value>
49     </init-param>
50   </servlet>
51   
52   <servlet-mapping>  
53       <servlet-name>krry_SSM</servlet-name>  
54       <url-pattern>/index</url-pattern>  
55   </servlet-mapping>  
56   
57   <!-- 能夠配*.do, *.action(瞭解) / (重點): 全部的請求都會被spring mvc解析,但必須對靜態資源文件進行過濾放行,建議你們使用這種方式 58  /* : 不建議你們使用 -->
59   <servlet-mapping>
60     <servlet-name>krry_SSM</servlet-name>
61     <url-pattern>/</url-pattern>
62   </servlet-mapping>
63  
64 </web-app>

 

這裏注意一點歡迎頁面,welcome-file-list通常狀況下只能使用靜態網頁,若是非要把他配置成SpringMVC的控制器(經過controller進入歡迎頁)URL就會報錯404,

解決方法:

在web.xml上首先設置

1   <welcome-file-list>
2     <welcome-file>index</welcome-file>
3   </welcome-file-list>

再增長一個/index 的映射

1   <servlet-mapping>  
2       <servlet-name>krry_SSM</servlet-name>  
3       <url-pattern>/index</url-pattern>  
4   </servlet-mapping>

最後在controller層添加一個首頁控制器獲得index的請求

1 @RequestMapping("/index")

 

controller層:

 1 package com.krry.controller.login;  2 
 3 import java.sql.Date;  4 import java.sql.Timestamp;  5 import java.text.SimpleDateFormat;  6 import java.util.UUID;  7 
 8 import javax.servlet.http.HttpServletRequest;  9 
 10 import org.springframework.beans.factory.annotation.Autowired;  11 import org.springframework.stereotype.Controller;  12 import org.springframework.web.bind.annotation.RequestMapping;  13 import org.springframework.web.bind.annotation.RequestMethod;  14 
 15 import com.krry.entity.User;  16 import com.krry.service.IUserService;  17 import com.krry.util.TmStringUtils;  18 
 19 /**
 20  * Controller層,做爲請求轉發  21  * 頁面全部路徑的訪問方法:控制層的命名空間+@RequestMapping的value  22  * 如這裏的/login/index.krry(後綴在xml文件配置)  23  * */
 24 @Controller  //表示是多例模式,每一個用戶返回的web層是不同的
 25 @RequestMapping("/login")  26 public class LoginController {  27 
 28  @Autowired  29     private IUserService userService;  30     
 31     /**
 32  * 若在下面的@RequestMapping前面加上@ResponseBody,  33  * 若方法是String類型則直接返回的是字符串,不會跳轉到該字符串的路徑jsp文件  34  *  35  * 因此要想跳轉到某一jsp頁面,不能加上@ResponseBody  36  * 這個@ResponseBody適合ajax返回的數據  37  *  38      */
 39     
 40     /**
 41  * 在控制層不加@ResponseBody的狀況下,return值默認是轉發到某路徑,不會顯示轉發路徑,顯示的是未轉發前的路徑  42  * 若要重定向,加上redirect:這裏默認是當前命名空間的轉發,要跳轉到另外一個control層,須要返回上一級../  43  *  44  這裏使用重定向,返回命名空間的上一級,重定向到命名空間爲Krry下的index  45  return "redirect:../index";  46         
 47  注意:  48  轉發不會顯示轉發路徑,顯示的是未轉發前的路徑  49  * 重定向顯示的是跳轉以後的路徑  50      */
 51     
 52     /**
 53  * 進入登陸界面  54  * @return
 55      */
 56     @RequestMapping("/index")  57     public String index(){  58 // ModelAndView modelAndView = new ModelAndView();  59 // modelAndView.setViewName("index/login"); //跳到此頁面  60 // return modelAndView;
 61         return "index/login";   //默認是轉發,不會顯示轉發路徑
 62  }  63     
 64     /**
 65  * 點擊登陸  66  * com.krry.controller.login  67  * 方法名:login  68  * @author krry  69  * @param request  70  * @return String  71  * @exception 
 72  * @since 1.0.0  73      */
 74     @RequestMapping(method=RequestMethod.POST,value="/logined")  75     public String login(HttpServletRequest request){  76         //獲取用戶和密碼
 77         String username = request.getParameter("username");  78         String password = request.getParameter("password");  79         
 80         //若是郵箱和密碼爲null,那麼就返回已null標識
 81         if(TmStringUtils.isEmpty(username) )return "index/allError";  82         if(TmStringUtils.isEmpty(password))return "index/allError";  83         
 84         //密碼進行加密處理
 85         password = TmStringUtils.md5Base64(password);  86         
 87         //根據郵箱或暱稱查詢,用戶是否存在
 88         User user = userService.getLogin(username);  89         
 90         //若是存在
 91         if(user!=null){  92             
 93             User userpas = userService.getpass(username, password);  94             if(userpas!=null){  95                 //若是密碼正確  96                 //將用戶信息放入到會話中...
 97                 request.getSession().setAttribute("user", user);  98                 
 99                 //這裏使用重定向,返回命名空間的上一級,重定向到命名空間爲Krry下的index.krry
100                 return "redirect:../index"; 101             }else{ 102                 //若是密碼錯誤
103                 System.out.println("密碼錯誤"); 104                 return "index/error"; 105  } 106         }else{ 107             //若是不存在,代碼郵箱和密碼輸入有誤
108             System.out.println("用戶不存在"); 109             return "index/error"; 110  } 111  } 112     
113     /**
114  * 退出登陸控制層 115  * com.krry.controller.login 116  * 方法名:logout 117  * @author krry 118  * @param request 119  * @return String 120  * @exception 
121  * @since 1.0.0 122      */
123     @RequestMapping(method=RequestMethod.GET,value="/logout") 124     public String logout(HttpServletRequest request){ 125         request.getSession().invalidate(); //清空session值
126         return "index/index"; 127  } 128     
129     /**
130  * 打開註冊界面層 131  * @return
132      */
133     @RequestMapping("/rege") 134     public String rege(){ 135 // ModelAndView modelAndView = new ModelAndView(); 136 // modelAndView.setViewName("index/login"); //跳到此頁面 137 // return modelAndView;
138         return "index/resgi"; 139  } 140     
141     /**
142  * 註冊控制層 143  * com.krry.controller.login 144  * 方法名:resig 145  * @author krry 146  * @param request 147  * @return String 148  * @exception 
149  * @since 1.0.0 150      */
151     @RequestMapping(method=RequestMethod.POST,value="/resig") 152     public String resig(HttpServletRequest request){ 153         //獲取用戶和密碼
154         String name = request.getParameter("username"); 155         String email = request.getParameter("email"); 156         String password = request.getParameter("password"); 157 
158         //若是郵箱和密碼爲null,那麼就返回已null標識
159         if(TmStringUtils.isEmpty(name) )return "index/allError"; 160         if(TmStringUtils.isEmpty(email))return "index/allError"; 161         if(TmStringUtils.isEmail(password))return "index/allError"; 162         
163         //密碼進行加密處理
164         password = TmStringUtils.md5Base64(password); 165         //根據暱稱查詢,用戶是否存在
166         User user1 = userService.getothernameres(name); 167         //根據帳號查詢,用戶是否存在
168         User user2 = userService.getemailres(email); 169         
170         //若存在
171         if(user1 != null){ //暱稱重複
172             return "index/allError"; 173  } 174         if(user2 != null){ //email重複
175             return "index/allError"; 176  } 177 
178         Date time = new Date(System.currentTimeMillis()); 179         
180         String id = UUID.randomUUID().toString(); 181         //執行到這裏,說明能夠註冊
182         User newUser = new User(id, name, password, email,time); 183         //調用註冊方法
184  userService.saveUser(newUser); 185         
186         //將信息設置session做用域
187         request.getSession().setAttribute("user", newUser); 188 
189         /**
190  * 這裏使用重定向,返回命名空間的上一級,重定向到index 191          */
192         return "redirect:../index"; 193  } 194     
195 }

 

 重要的點,以上的說到了,還有一些前端頁面、數據庫操做就不在這展現了

以上ssm整合的連接展現:https://www.ainyi.com/krry_SSM

 

JavaWeb容器初始化過程

相關文章
相關標籤/搜索