Spring MVC 框架搭建及詳解

現在主流的Web MVC框架除了Struts這個主力 外,其次就是Spring MVC了,因此這也是作爲一名程序員需要掌握的主流框架,框架選擇多了,應對多變的需求和業務時,可實行的方案自然就多了。不過要想靈活運用Spring MVC來應對大多數的Web開發,就必須要掌握它的配置及原理。

  一、Spring MVC環境搭建:(Spring 2.5.6 + Hibernate 3.2.0)

  1. jar包引入

  Spring 2.5.6:spring.jar、spring-webmvc.jar、commons-logging.jar、cglib-nodep-2.1_3.jar

  Hibernate 3.6.8:hibernate3.jar、hibernate-jpa-2.0-api-1.0.1.Final.jar、antlr-2.7.6.jar、commons-collections-3.1、dom4j-1.6.1.jar、javassist-3.12.0.GA.jar、jta-1.1.jar、slf4j-api-1.6.1.jar、slf4j-nop-1.6.4.jar、相應數據庫的驅動jar包

  2. web.xml配置(部分)

01 <!-- Spring MVC配置 -->
02 <!-- ====================================== -->
03 <servlet>
04     <servlet-name>spring</servlet-name>
05     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
06     <!-- 可以自定義servlet.xml配置文件的位置和名稱,默認爲WEB-INF目錄下,名稱爲[<servlet-name>]-servlet.xml,如spring-servlet.xml
07     <init-param>
08         <param-name>contextConfigLocation</param-name>
09         <param-value>/WEB-INF/spring-servlet.xml</param-value>  默認
10     </init-param>
11     -->
12     <load-on-startup>1</load-on-startup>
13 </servlet>
14  
15 <servlet-mapping>
16     <servlet-name>spring</servlet-name>
17     <url-pattern>*.do</url-pattern>
18 </servlet-mapping>
19    
20  
21  
22 <!-- Spring配置 -->
23 <!-- ====================================== -->
24 <listener>
25     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
26 </listener>
27    
28  
29 <!-- 指定Spring Bean的配置文件所在目錄。默認配置在WEB-INF目錄下 -->
30 <context-param>
31     <param-name>contextConfigLocation</param-name>
32     <param-value>classpath:config/applicationContext.xml</param-value>
33 </context-param>

  3. spring-servlet.xml配置

  spring-servlet這個名字是因爲上面web.xml中<servlet-name>標籤配的值爲spring(<servlet-name>spring</servlet-name>),再加上“-servlet”後綴而形成的spring-servlet.xml文件名,如果改爲springMVC,對應的文件名則爲springMVC-servlet.xml。

01 <?xml version="1.0" encoding="UTF-8"?>
02 <beans xmlns="http://www.springframework.org/schema/beans"    
03        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"    
04         xmlns:context="http://www.springframework.org/schema/context"    
05    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
06        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
07        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
08        http://www.springframework.org/schema/context <a href="http://www.springframework.org/schema/context/spring-context-3.0.xsd">http://www.springframework.org/schema/context/spring-context-3.0.xsd</a>">
09  
10     <!-- 啓用spring mvc 註解 -->
11     <context:annotation-config />
12  
13     <!-- 設置使用註解的類所在的jar包 -->
14     <context:component-scan base-package="controller"></context:component-scan>
15  
16     <!-- 完成請求和註解POJO的映射 -->
17     <beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
18  
19     <!-- 對轉向頁面的路徑解析。prefix:前綴, suffix:後綴 -->
20     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/jsp/" p:suffix=".jsp" />
21 </beans>

  4. applicationContext.xml配置

01 <?xml version="1.0" encoding="UTF-8"?>
02 <beans xmlns="http://www.springframework.org/schema/beans"
03         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04         xmlns:aop="http://www.springframework.org/schema/aop"
05         xmlns:tx="http://www.springframework.org/schema/tx"
06         xsi:schemaLocation="
07             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
08             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
09             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
10  
11     <!-- 採用hibernate.cfg.xml方式配置數據源 -->
12     <bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
13         <property name="configLocation">
14             <value>classpath:config/hibernate.cfg.xml</value>
15         </property>
16     </bean>
17      
18     <!-- 將事務與Hibernate關聯 -->
19     <bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
20         <property name="sessionFactory">
21             <ref local="sessionFactory"/>
22         </property>
23     </bean>
24      
25     <!-- 事務(註解 )-->
26     <tx:annotation-driven transaction-manager="transactionManager"proxy-target-class="true"/>
27  
28    <!-- 測試Service -->
29    <bean id="loginService" class="service.LoginService"></bean>
30  
31     <!-- 測試Dao -->
32     <bean id="hibernateDao" class="dao.HibernateDao">
33         <property name="sessionFactory" ref="sessionFactory"></property>
34     </bean>
35 </beans>

 

  二、詳解

  Spring MVC與Struts從原理上很相似(都是基於MVC架構),都有一個控制頁面請求的Servlet,處理完後跳轉頁面。看如下代碼(註解):

01 package controller;
02  
03 import javax.servlet.http.HttpServletRequest;
04  
05 import org.springframework.stereotype.Controller;
06 import org.springframework.web.bind.annotation.RequestMapping;
07 import org.springframework.web.bind.annotation.RequestParam;
08  
09 import entity.User;
10  
11 @Controller  //類似Struts的Action
12 public class TestController {
13  
14     @RequestMapping("test/login.do")  // 請求url地址映射,類似Struts的action-mapping
15     publicString testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) {
16         // @RequestParam是指請求url地址映射中必須含有的參數(除非屬性required=false)
17         // @RequestParam可簡寫爲:@RequestParam("username")
18  
19         if (!"admin".equals(username) || !"admin".equals(password)) {
20             return"loginError"// 跳轉頁面路徑(默認爲轉發),該路徑不需要包含spring-servlet配置文件中配置的前綴和後綴
21         }
22         return "loginSuccess";
23     }
24  
25     @RequestMapping("/test/login2.do")
26     public ModelAndView testLogin2(String username, String password, int age){
27         // request和response不必非要出現在方法中,如果用不上的話可以去掉
28         // 參數的名稱是與頁面控件的name相匹配,參數類型會自動被轉換
29          
30         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
31             return newModelAndView("loginError"); // 手動實例化ModelAndView完成跳轉頁面(轉發),效果等同於上面的方法返回字符串
32         }
33         return new ModelAndView(newRedirectView("../index.jsp"));  // 採用重定向方式跳轉頁面
34         // 重定向還有一種簡單寫法
35         // return new ModelAndView("redirect:../index.jsp");
36     }
37  
38     @RequestMapping("/test/login3.do")
39     public ModelAndView testLogin3(User user) {
40         // 同樣支持參數爲表單對象,類似於Struts的ActionForm,User不需要任何配置,直接寫即可
41         String username = user.getUsername();
42         String password = user.getPassword();
43         int age = user.getAge();
44          
45         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
46             return new ModelAndView("loginError");
47         }
48         return new ModelAndView("loginSuccess");
49     }
50  
51     @Resource(name = "loginService")  // 獲取applicationContext.xml中bean的id爲loginService的,並注入
52     privateLoginService loginService;  //等價於spring傳統注入方式寫get和set方法,這樣的好處是簡潔工整,省去了不必要得代碼
53  
54     @RequestMapping("/test/login4.do")
55     public String testLogin4(User user) {
56         if (loginService.login(user) == false) {
57             return "loginError";
58         }
59         return "loginSuccess";
60     }
61 }

  以上4個方法示例,是一個Controller裏含有不同的請求url,也可以採用一個url訪問,通過url參數來區分訪問不同的方法,代碼如下:

01 package controller;
02  
03 import org.springframework.stereotype.Controller;
04 import org.springframework.web.bind.annotation.RequestMapping;
05 import org.springframework.web.bind.annotation.RequestMethod;
06  
07 @Controller
08 @RequestMapping("/test2/login.do")  // 指定唯一一個*.do請求關聯到該Controller
09 public class TestController2 {
10      
11     @RequestMapping
12     public String testLogin(String username, String password, int age) {
13         // 如果不加任何參數,則在請求/test2/login.do時,便默認執行該方法
14          
15         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
16             return "loginError";
17         }
18         return "loginSuccess";
19     }
20  
21     @RequestMapping(params = "method=1", method=RequestMethod.POST)
22     public String testLogin2(String username, String password) {
23         // 依據params的參數method的值來區分不同的調用方法
24         // 可以指定頁面請求方式的類型,默認爲get請求
25          
26         if (!"admin".equals(username) || !"admin".equals(password)) {
27             return "loginError";
28         }
29         return "loginSuccess";
30     }
31      
32     @RequestMapping(params = "method=2")
33     public String testLogin3(String username, String password, int age) {
34         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
35             return "loginError";
36         }
37         return "loginSuccess";
38     }
39 }

  其實RequestMapping在Class上,可看做是父Request請求url,而RequestMapping在方法上的可看做是子Request請求url,父子請求url最終會拼起來與頁面請求url進行匹配,因此RequestMapping也可以這麼寫:

01 package controller;
02  
03 import org.springframework.stereotype.Controller;
04 import org.springframework.web.bind.annotation.RequestMapping;
05  
06 @Controller
07 @RequestMapping("/test3/*")  // 父request請求url
08 public class TestController3 {
09  
10     @RequestMapping("login.do")  // 子request請求url,拼接後等價於/test3/login.do
11     public String testLogin(String username, String password, int age) {
12         if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
13             return "loginError";
14         }
15         return "loginSuccess";
16     }
17 }

 

  三、結束語

  掌握以上這些Spring MVC就已經有了很好的基礎了,幾乎可應對與任何開發,在熟練掌握這些後,便可更深層次的靈活運用的技術,如多種視圖技術,例如 Jsp、Velocity、Tiles、iText 和 POI。Spring MVC框架並不知道使用的視圖,所以不會強迫您只使用 JSP 技術。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章