1. 程式人生 > >Spring-mvc學習心得(一)

Spring-mvc學習心得(一)

Sun JDK1.6.0_13 ; MyEslipse10 ; Tomcat ; 谷歌瀏覽器 ; 

本次操作將用springmvc通過輸入網址,返回所需的網頁,並在控制檯列印輸出資訊(使用註解的方式)

網頁輸出:

控制檯列印:

建立Springmvc框架,需如下步驟:

1. 匯入所需jar包

1.1 匯入spring以及springmvc所需jar包

最少需要匯入如下6個jar包:

  spring-beans-3.2.13.RELEASE.jar

  spring-context-3.2.13.RELEASE.jar

  spring-core-3.2.13.RELEASE.jar

  spring-expression-3.2.13.RELEASE.jar

  spring-web-3.2.13.RELEASE.jar

  spring-webmvc-3.2.13.RELEASE.jar

jar包在壓縮包解壓後 spring-framework-3.2.13.RELEASE-dist資料夾 > spring-framework-3.2.13.RELEASE資料夾 > libs資料夾下尋找,將jar包複製到web專案中WebRoot > WEB-INF lib資料夾下

1.2 匯入日誌檔案所需jar包

log4j所需jar包 百度網盤連結:

log4j所需jar包

將日誌壓縮包裡的4個jar包複製到web專案中WebRoot > WEB-INF lib資料夾下,然後在web專案下建立resources目錄(Source Folder),將log4j.properties檔案複製到resources資料夾下,此為log4j配置檔案,備用

選中WebRoot > WEB-INF lib資料夾下所有jar包,右擊Build Path > Configure Build Path...

匯入jar包步驟完成

2. 配置web.xml

springmvc也是一種servlet,所以需要通過配置web.xml檔案,讓專案去識別springmvc

開啟WebRoot > WEB-INF 資料夾下的web.xml檔案

然後我配置的程式碼如下,會在程式碼中進行分析:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 下面是我的配置 -->
  
  <!-- 因為springmvc也是servlet的一種,所以通過配置servlet讓專案識別 -->
  <servlet>
  	<!-- 因為本專案是springmvc,故servlet命名為springmvc,以供識別 -->
  	<servlet-name>springmvc</servlet-name>
  	<!-- 
  		命名為springmvc的servlet是DispatcherServlet型別的,
  		Ctrl+Shift+H搜尋該類DispatcherServlet,賦予這個類的完全限定名,
  		DispatcherServlet也是springmvc的入口,這裡不需要過深涉及
  	 -->
  	<servlet-class>
  		org.springframework.web.servlet.DispatcherServlet
  	</servlet-class>
  	<!-- 設定初始化引數,將我們要配置的springmvc的配置檔案地址匯入 -->
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:springmvc-servlet.xml</param-value>
  	</init-param>
  	<!-- 此處設定1,表示spring容器在啟動的時候就要載入這個DispatcherServlet型別的servlet,即自啟動 -->
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <!-- servlet-mapping標籤作用是截獲請求的 -->
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<!-- /表示截獲根目錄下的所有請求 -->
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

這段配置資訊的作用是,在spring的容器啟動的時候就載入這個springmvc,然後在有請求出現時,截獲所有請求,交給springmvc-servlet.xml檔案配置的controller(控制器)去處理,後面會涉及到,此處不做詳解。

3. 下邊我們開始編寫springmvc-servlet.xml配置檔案。

(1) 首先建立一個xml檔案,在resources目錄下右擊New > File,命名為springmvc-servlet.xml。

(2) 在檔案中匯入頭部約束配置,開啟下載的spring壓縮包資料夾,在以下路徑:spring-framework-3.2.13.RELEASE-dist\spring-framework-3.2.13.RELEASE\docs\spring-framework-reference\html資料夾下,搜尋檔案mvc.html並用瀏覽器開啟。在17.3.1下或Ctrl+F搜尋關鍵詞"17.3.1",這個目錄下的程式碼片段,複製如下部分貼上到springmvc-servlet.xml中

<?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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

</beans>

然後,再在mvc.html網頁中搜索"xmlns:mvc",將定位到的程式碼中的如下程式碼插入上述程式碼中,按上述程式碼格式插入(後面有完整程式碼):

xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd

此時頭部約束完成,我們開始編寫配置檔案。

(3) 此例中完整的springmvc-serlvet.xml配置檔案如下(使用註解的方式):

<?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:mvc="http://www.springframework.org/schema/mvc"
    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://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">

	<!-- 
		配置掃描註解,將com.zb.controller目錄下的註解掃描註冊,
	 	沒有這句話,掃描不到註解,帶有註解的JavaBean也將是普通的java程式碼
	 -->
	<context:component-scan base-package="com.zb.controller" />
	<!-- 該標籤可以將url自動對映到controller上 -->
	<mvc:annotation-driven />

	<!-- 
		配置檢視解析器
	 	基於InternalResourceViewResolver類,Ctrl+Shift+H尋找它的完整限定名,是servlet的
	 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 
			此為字首,
			controller(控制器)的返回值將自動在前後加上字首字尾,
			此例中,controller返回index字串,加上前後綴的完整url是:/WEB-INF/jsp/index.jsp,
			成功定位到此jsp頁面
		 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!-- 此為字尾 -->
		<property name="suffix" value=".jsp" />
	</bean>
        
</beans>

<mvc:annotation-driven>:會自動註冊RequestMappingHandlerMapping與RequestMappingHandlerAdapter兩個Bean,這是Spring MVC為@Controller分發請求所必需的,並且提供了資料繫結支援。

4. 編寫controller(控制器)

新建一個類MyController,所在包com.zb.controller下,程式碼如下:

package com.zb.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MyController {
	
	private Logger logger = Logger.getLogger(MyController.class);
	
	@RequestMapping("/welcome")
	public ModelAndView index(){
		logger.info("Hello,springmvc!");
		return new ModelAndView("index");
	}
}

@Controller:讓springmvc-servlet.xml中的掃描到,並將此類識別為controller(控制器),並自動註冊

@RequestMapping("/welcome"):此註解的作用為,將“/welcome”的請求識別並定位用此方法處理請求,使此次註解可以在這個類中寫很多的處理方法,只要用此註解加以標示,就可以分清,不必要定義n多個類

logger.info("Hello,springmvc!"); : 在控制檯列印日誌,用來讓我們知道程式執行到此方法

return new ModelAndView("index"); :此處直接返回字串“index”,用於url拼接,尋找此將jsp頁面

5. 釋出執行

最後在專案目錄/WEB-INF/下建立資料夾jsp,在jsp中建立名為index的jsp頁面。完成最終編寫

本例使用Tomcat,釋出細節在此不再贅述。執行結果如本文開頭所示。

本例使用的是註解的方式掃描controller,還有手動編寫 配置處理器對映 HandlerMapping 標籤的方式:

<!-- 配置處理器對映 HandlerMapping -->
<bean name="/welcome" class="com.zb.controller.MyController" />

而controller的編寫如下:

package com.zb.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class MyController extends AbstractController {

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		// TODO Auto-generated method stub
		return new ModelAndView("index");
	}
}

此類方式,一句對映對應一個controller,在對映較多的情況下將非常繁瑣,所以常用註解的方式