Spring MVC 框架搭建及詳解

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

  1、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.一、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配置(部分)

java

Java代碼 複製代碼 收藏代碼
  1. <!-- Spring MVC配置 -->
  2. <!-- ====================================== -->
  3. <servlet>
  4. <servlet-name>spring</servlet-name>
  5. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  6. <!-- 能夠自定義servlet.xml配置文件的位置和名稱,默認爲WEB-INF目錄下,名稱爲[<servlet-name>]-servlet.xml,如spring-servlet.xml
  7. <init-param>
  8. <param-name>contextConfigLocation</param-name>
  9. <param-value>/WEB-INF/spring-servlet.xml</param-value> 默認
  10. </init-param>
  11. -->
  12. <load-on-startup>1</load-on-startup>
  13. </servlet>
  14. <servlet-mapping>
  15. <servlet-name>spring</servlet-name>
  16. <url-pattern>*.do</url-pattern>
  17. </servlet-mapping>
  18. <!-- Spring配置 -->
  19. <!-- ====================================== -->
  20. <listener>
  21. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  22. </listener>
  23. <!-- 指定Spring Bean的配置文件所在目錄。默認配置在WEB-INF目錄下 -->
  24. <context-param>
  25. <param-name>contextConfigLocation</param-name>
  26. <param-value>classpath:config/applicationContext.xml</param-value>
  27. </context-param>
<!-- Spring MVC配置 -->
<!-- ====================================== -->
<servlet>
	<servlet-name>spring</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<!-- 能夠自定義servlet.xml配置文件的位置和名稱,默認爲WEB-INF目錄下,名稱爲[<servlet-name>]-servlet.xml,如spring-servlet.xml
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring-servlet.xml</param-value>  默認
	</init-param>
	-->
	<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
	<servlet-name>spring</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>
  


<!-- Spring配置 -->
<!-- ====================================== -->
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  

<!-- 指定Spring Bean的配置文件所在目錄。默認配置在WEB-INF目錄下 -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:config/applicationContext.xml</param-value>
</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。

node

Java代碼 複製代碼 收藏代碼
  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. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  6. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  7. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  8. 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>">
  9. <!-- 啓用spring mvc 註解 -->
  10. <context:annotation-config />
  11. <!-- 設置使用註解的類所在的jar包 -->
  12. <context:component-scan base-package="controller"></context:component-scan>
  13. <!-- 完成請求和註解POJO的映射 -->
  14. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
  15. <!-- 對轉向頁面的路徑解析。prefix:前綴, suffix:後綴 -->
  16. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />
  17. </beans>
<?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:p="http://www.springframework.org/schema/p"     
        xmlns:context="http://www.springframework.org/schema/context"     
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
       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>">

	<!-- 啓用spring mvc 註解 -->
	<context:annotation-config />

	<!-- 設置使用註解的類所在的jar包 -->
	<context:component-scan base-package="controller"></context:component-scan>

	<!-- 完成請求和註解POJO的映射 -->
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

	<!-- 對轉向頁面的路徑解析。prefix:前綴, suffix:後綴 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />
</beans>



4. applicationContext.xml配置

程序員

Java代碼 複製代碼 收藏代碼
  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:aop="http://www.springframework.org/schema/aop"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  9. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
  10. <!-- 採用hibernate.cfg.xml方式配置數據源 -->
  11. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  12. <property name="configLocation">
  13. <value>classpath:config/hibernate.cfg.xml</value>
  14. </property>
  15. </bean>
  16. <!-- 將事務與Hibernate關聯 -->
  17. <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  18. <property name="sessionFactory">
  19. <ref local="sessionFactory"/>
  20. </property>
  21. </bean>
  22. <!-- 事務(註解 )-->
  23. <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
  24. <!-- 測試Service -->
  25. <bean id="loginService" class="service.LoginService"></bean>
  26. <!-- 測試Dao -->
  27. <bean id="hibernateDao" class="dao.HibernateDao">
  28. <property name="sessionFactory" ref="sessionFactory"></property>
  29. </bean>
  30. </beans>
<?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: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-2.5.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- 採用hibernate.cfg.xml方式配置數據源 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation">
			<value>classpath:config/hibernate.cfg.xml</value>
		</property>
	</bean>
	
	<!-- 將事務與Hibernate關聯 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref local="sessionFactory"/>
		</property>
	</bean>
	
	<!-- 事務(註解 )-->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

	<!-- 測試Service -->
	<bean id="loginService" class="service.LoginService"></bean>

	<!-- 測試Dao -->
	<bean id="hibernateDao" class="dao.HibernateDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
</beans>



  2、詳解

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



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

web

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import entity.User;

@Controller  //相似Struts的Action
public class TestController {

	@RequestMapping("test/login.do")  // 請求url地址映射,相似Struts的action-mapping
	public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) {
		// @RequestParam是指請求url地址映射中必須含有的參數(除非屬性required=false)
		// @RequestParam可簡寫爲:@RequestParam("username")

		if (!"admin".equals(username) || !"admin".equals(password)) {
			return "loginError"; // 跳轉頁面路徑(默認爲轉發),該路徑不須要包含spring-servlet配置文件中配置的前綴和後綴
		}
		return "loginSuccess";
	}

	@RequestMapping("/test/login2.do")
	public ModelAndView testLogin2(String username, String password, int age){
		// request和response沒必要非要出如今方法中,若是用不上的話能夠去掉
		// 參數的名稱是與頁面控件的name相匹配,參數類型會自動被轉換
		
		if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
			return new ModelAndView("loginError"); // 手動實例化ModelAndView完成跳轉頁面(轉發),效果等同於上面的方法返回字符串
		}
		return new ModelAndView(new RedirectView("../index.jsp"));  // 採用重定向方式跳轉頁面
		// 重定向還有一種簡單寫法
		// return new ModelAndView("redirect:../index.jsp");
	}

	@RequestMapping("/test/login3.do")
	public ModelAndView testLogin3(User user) {
		// 一樣支持參數爲表單對象,相似於Struts的ActionForm,User不須要任何配置,直接寫便可
		String username = user.getUsername();
		String password = user.getPassword();
		int age = user.getAge();
		
		if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
			return new ModelAndView("loginError");
		}
		return new ModelAndView("loginSuccess");
	}

	@Resource(name = "loginService")  // 獲取applicationContext.xml中bean的id爲loginService的,並注入
	private LoginService loginService;  //等價於spring傳統注入方式寫get和set方法,這樣的好處是簡潔工整,省去了沒必要要得代碼

	@RequestMapping("/test/login4.do")
	public String testLogin4(User user) {
		if (loginService.login(user) == false) {
			return "loginError";
		}
		return "loginSuccess";
	}
}



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

查看源碼打印?


spring

Java代碼 複製代碼 收藏代碼
  1. package controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. @Controller
  5. @RequestMapping("/test3/*") // 父request請求url
  6. public class TestController3 {
  7. @RequestMapping("login.do") // 子request請求url,拼接後等價於/test3/login.do
  8. public String testLogin(String username, String password, int age) {
  9. if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
  10. return "loginError";
  11. }
  12. return "loginSuccess";
  13. }
  14. }
package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/test3/*")  // 父request請求url
public class TestController3 {

	@RequestMapping("login.do")  // 子request請求url,拼接後等價於/test3/login.do
	public String testLogin(String username, String password, int age) {
		if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
			return "loginError";
		}
		return "loginSuccess";
	}
}



  3、結束語

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

相關文章
相關標籤/搜索