目前主流的Web MVC框架,除了Struts這個主力 外,還有Spring MVC,主要是由于Spring MVC配置比較簡單,使用起來也十分明了,非常靈活,與Spring 集成較好,對RESTful API的支持也比struts要好。
MyBatis是ibatis的升級版,作為hibernate的老對手,它 是一個可以自定義SQL、存儲過程和高級映射的持久層框架。
與hibernate的主要區別就是mybatis是半自動化的,而hibernate是全自動的,所以當應用需求越來越復雜的時候,自動化的sql顯得比較笨拙。
由于前段時間接了個項目要用springmvc做,所以我抱著練手的態度,又玩起了整合框架的游戲。經常搭框架的人應該都清楚,框架搭建的核心就是配置文件。所以我主要貼下幾個配置文件的代碼。還是那句話,我都是寫好配置文件之后,運行報錯再加jar。這里列一下我用的jar包(應該是最少的):
備注:上圖有一些額外的jar,比如我用的數據庫連接池是阿里巴巴的druid、日志框架式logback,所以引入了相關jar。關于這兩個框架的使用和配置都是非常簡單的,所以這里就不細說。
1.整合SpringMVC
springMybatis-servlet.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
|
<? 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:context = "http://www.springframework.org/schema/context" xmlns:mvc = "http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 啟用spring mvc 注解--> < mvc:annotation-driven > </ mvc:annotation-driven > <!-- 自動掃描的包名 ,使Spring支持自動檢測組件,如注解的Controller--> < context:component-scan base-package = "com.alibaba.controller" /> < context:component-scan base-package = "com.alibaba.service" /> <!-- 視圖解析器:定義跳轉的文件的前后綴 --> < bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver" > < property name = "prefix" value = "/WEB-INF/jsp/" /> < property name = "suffix" value = ".jsp" /> <!--可為空,方便實現自已的依據擴展名來選擇視圖解釋類的邏輯 --> </ bean > <!--配置攔截器, 多個攔截器,順序執行 --> < mvc:interceptors > < mvc:interceptor > <!-- 匹配的是url路徑 --> < mvc:mapping path = "/" /> < mvc:mapping path = "/user/**" /> < mvc:mapping path = "/test/**" /> < bean class = "com.alibaba.interceptor.CommonInterceptor" ></ bean > </ mvc:interceptor > <!-- 當設置多個攔截器時,先按順序調用preHandle方法,然后逆序調用每個攔截器的postHandle和afterCompletion方法 --> </ mvc:interceptors > </ beans > |
2.整合Mybatis
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
|
<? 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:mybatis = "http://mybatis.org/schema/mybatis-spring" xmlns:context = "http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 該包下的類支持注解,表示會被當作{@code mybatis mapper}處理 配置了之后表示可以自動引入mapper類--> < mybatis:scan base-package = "com.alibaba.dao" /> <!--引入屬性文件 --> < context:property-placeholder location = "classpath:configuration.properties" /> <!--數據庫連接--> < bean id = "dataSource" class = "com.alibaba.druid.pool.DruidDataSource" init-method = "init" destroy-method = "close" > < property name = "url" value = "${jdbc.url}" /> < property name = "username" value = "${jdbc.username}" /> < property name = "password" value = "${jdbc.password}" /> <!-- 配置初始化大小、最小、最大 --> < property name = "initialSize" >< value >1</ value ></ property > < property name = "maxActive" >< value >5</ value ></ property > < property name = "minIdle" >< value >1</ value ></ property > <!-- 配置獲取連接等待超時的時間 --> < property name = "maxWait" >< value >60000</ value ></ property > <!-- 配置監控統計攔截的filters --> < property name = "filters" >< value >stat</ value ></ property > <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 --> < property name = "timeBetweenEvictionRunsMillis" >< value >60000</ value ></ property > <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 --> < property name = "minEvictableIdleTimeMillis" >< value >300000</ value ></ property > <!-- <property name="validationQuery"><value>SELECT 'x'</value></property> <property name="testWhileIdle"><value>true</value></property> <property name="testOnBorrow"><value>false</value></property> <property name="testOnReturn"><value>false</value></property> <property name="poolPreparedStatements"><value>true</value></property> <property name="maxOpenPreparedStatements"><value>20</value></property> --> </ bean > <!-- mybatis配置 --> < bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" > < property name = "dataSource" ref = "dataSource" /> </ bean > </ beans > |
3.web.xml整合SpringMVC和Mybatis
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
<? 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" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version = "3.0" > <!-- 該servlet為tomcat,jetty等容器提供,將靜態資源映射從/改為/static/目錄,如原來訪問 http://localhost/foo.css ,現在http://localhost/static/foo.css --> <!-- 不攔截靜態文件 --> < servlet-mapping > < servlet-name >default</ servlet-name > < url-pattern >/js/*</ url-pattern > < url-pattern >/css/*</ url-pattern > < url-pattern >/images/*</ url-pattern > < url-pattern >/fonts/*</ url-pattern > </ servlet-mapping > <!-- 配置字符集 --> < filter > < filter-name >encodingFilter</ filter-name > < filter-class >org.springframework.web.filter.CharacterEncodingFilter</ filter-class > < init-param > < param-name >encoding</ param-name > < param-value >UTF-8</ param-value > </ init-param > < init-param > < param-name >forceEncoding</ param-name > < param-value >true</ param-value > </ init-param > </ filter > < filter-mapping > < filter-name >encodingFilter</ filter-name > < url-pattern >/*</ url-pattern > </ filter-mapping > <!-- 初始化 DispatcherServlet時,該框架在 web應用程序WEB-INF目錄中尋找一個名為[servlet-名稱]-servlet.xml的文件, 并在那里定義相關的Beans,重寫在全局中定義的任何Beans --> < servlet > < servlet-name >springMybatis</ servlet-name > < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class > < load-on-startup >1</ load-on-startup > </ servlet > < servlet-mapping > < servlet-name >springMybatis</ servlet-name > <!-- 所有的的請求,都會被DispatcherServlet處理 --> < url-pattern >/</ url-pattern > </ servlet-mapping > < context-param > < param-name >contextConfigLocation</ param-name > < param-value >/WEB-INF/config/spring-*.xml</ param-value > </ context-param > < listener > < listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class > </ listener > <!-- druid web 監控 --> < servlet > < servlet-name >DruidStatView</ servlet-name > < servlet-class >com.alibaba.druid.support.http.StatViewServlet</ servlet-class > </ servlet > < servlet-mapping > < servlet-name >DruidStatView</ servlet-name > < url-pattern >/druid/*</ url-pattern > </ servlet-mapping > < error-page > < error-code >404</ error-code > < location >/error/404.jsp</ location > </ error-page > < error-page > < error-code >500</ error-code > < location >/error/500.jsp</ location > </ error-page > </ web-app > |
4.logback.xml日志配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<? xml version = "1.0" encoding = "UTF-8" ?> < configuration > < appender name = "STDOUT" class = "ch.qos.logback.core.ConsoleAppender" > < encoder > < pattern >%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</ pattern > </ encoder > </ appender > < logger name = "test.LogbackTest" level = "TRACE" /> < logger name = "com.alibaba.controller.TestController" level = "TRACE" /> < logger name = "org.springframework.web.servlet.DispatcherServlet" level = "DEBUG" /> < logger name = "druid.sql" level = "INFO" /> <!-- 如果spring-config里面沒有配置slf4j,就不會顯示sql日志,logback只是slf4j的一個實現 --> < root level = "debug" > < appender-ref ref = "STDOUT" /> </ root > </ configuration > |
5.configuration.properties配置
1
2
3
|
jdbc.url=jdbc\:mysql\://localhost\:3306/druid?useUnicode\=true&characterEncoding\=UTF-8&zeroDateTimeBehavior\=convertToNull jdbc.username=root jdbc.password=123456 |
6.測試搭建是否成功,后臺代碼
首先是登錄,用了加密,可以去掉
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
50
51
52
53
54
55
56
57
58
59
|
package com.alibaba.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.digest.DigestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.alibaba.model.User; import com.alibaba.service.UserService; import com.alibaba.util.RequestUtil; /** * @author tfj * 2014-7-26 */ @Controller public class SystemController { private final Logger log = LoggerFactory.getLogger(SystemController. class ); @Resource private UserService userService; @RequestMapping (value = "/" ,method = RequestMethod.GET) public String home() { log.info( "返回首頁!" ); return "index" ; } @RequestMapping (value = "/test/hello" ,method = RequestMethod.GET) public String testHello() { log.info( "執行了testHello方法!" ); return "testHello" ; } @RequestMapping (value = "/login" ,method = RequestMethod.POST) public String testLogin(HttpServletRequest request, @RequestParam String username, @RequestParam String password) { log.info( "執行了testLogin方法!" ); User user = userService.findUserByName(username); if (user!= null ){ if (user.getPassword().equals(DigestUtils.md5Hex(password))){ request.getSession().setAttribute( "userId" , user.getId()); request.getSession().setAttribute( "user" , username); return "redirect:" + RequestUtil.retrieveSavedRequest(); //跳轉至訪問頁面 } else { log.info( "密碼錯誤" ); request.getSession().setAttribute( "message" , "用戶名密碼錯誤,請重新登錄" ); return "login" ; } } else { log.info( "用戶名不存在" ); request.getSession().setAttribute( "message" , "用戶名不存在,請重新登錄" ); return "login" ; } } } |
關于service和model就不寫了,寫一下mybatis的mapper類映射
1
2
3
4
5
6
7
|
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> < mapper namespace = "com.alibaba.dao.UserMapper" > < select id = "findUserByName" resultType = "com.alibaba.model.User" > select id, username , password from sysuser where username = #{username} </ select > </ mapper > |
7.前臺jsp主要是登錄和登錄成功的頁面,就不寫了
貼一下截圖:
到此,springmvc+mybatis整合成功。后續復雜的功能待添加
注意事項
1.框架中關于druid和logback的配置都是從官網上copy下來的,所以都是最基本的,讀者可以忽略,也可以換成讀者熟悉的數據庫組件和日志框架,如c3p0和log4j。
2.代碼里加入了權限管理,即訪問前需登錄,登錄后跳轉至待訪問頁面,關于springmvc的權限管理請看:http://www.jfrwli.cn/article/84142.html
3.本文是從我的測試代碼里剝離出來的最簡單的也是最基本的代碼,有些沒剝離干凈的地方還請見諒。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/tonytfjing/article/details/39203121