top
Loading...
SpringMVC開發快速入門

這篇文章將教你快速地上手使用 Spring 框架,如果你手上有一本《Spring in Action》, 那么你最好從第三部分"Spring 在 Web 層的應用--建立 Web 層"開始看, 否則那將是一場惡夢!

首先, 我需要在你心里建立起 Spring MVC 的基本概念. 基于 Spring 的 Web 應用程序接收到 http://localhost:8080/hello.do(事實上請求路徑是 /hello.do) 的請求后, Spring 將這個請求交給一個名為 helloController 的程序進行處理, helloController 再調用 一個名為 hello.jsp 的 jsp 文件生成 HTML 代碼發給用戶的瀏覽器顯示. 上面的名稱(/hello.do, helloController, hello.jsp) 都是變量, 你可以更改.

在 Spring MVC 中, jsp 文件中盡量不要有 Java 代碼, 只有 HTML 代碼和"迭代(forEach)"與"判斷(if)"兩個jstl標簽. jsp 文件只作為渲染(或稱為視圖 View)模板使用.

好了, 我們開始吧. 首先我們需要一個放在 WEB-INF 目錄下的 web.xml 文件:

web.xml:
 1 <?xml version="1.0" encoding="UTF-8"?>
2
3 web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
6 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
7
8 context-param
9 param-namecontextConfigLocation</param-name>
10 param-value
11 /WEB-INF/database.xml
12 /WEB-INF/applicationContext.xml
13 </param-value>
14 </context-param>
15
16 listener
17 listener-classorg.springframework.web.context.ContextLoaderListener</listener-class>
18 </listener>
19
20 filter
21 filter-nameencodingFilter</filter-name>
22 filter-classorg.springframework.web.filter.CharacterEncodingFilter</filter-class>
23 init-param
24 param-nameencoding</param-name>
25 param-valueUTF-8</param-value>
26 </init-param>
27 </filter>
28
29 filter-mapping
30 filter-nameencodingFilter</filter-name>
31 url-pattern*.do</url-pattern>
32 </filter-mapping>
33
34 servlet
35 servlet-nameideawu</servlet-name>
36 servlet-classorg.springframework.web.servlet.DispatcherServlet</servlet-class>
37 load-on-startup1</load-on-startup>
38 </servlet>
39
40 servlet-mapping
41 servlet-nameideawu</servlet-name>
42 url-pattern*.do</url-pattern>
43 </servlet-mapping>
44
45 welcome-file-list
46 welcome-fileindex.jsp</welcome-file>
47 welcome-fileindex.html</welcome-file>
48 </welcome-file-list>
49
50 jsp-config
51 taglib
52 taglib-urihttp://java.sun.com/jsp/jstl/core</taglib-uri>
53 taglib-location/WEB-INF/tld/c.tld</taglib-location>
54 </taglib>
55 taglib
56 taglib-urihttp://java.sun.com/jsp/jstl/fmt</taglib-uri>
57 taglib-location/WEB-INF/tld/fmt.tld</taglib-location>
58 </taglib>
59 </jsp-config>
60
61 </web-app>

它配置了以下功能:

  • 配置 DispatcherServlet (servlet 標簽), 它是一個 Java Servlet 程序. 我們將它命名為 ideawu. 然后我們再配置 Servlet 映射(servlet-mapping 標簽), 也就是你希望哪些請求被DispatcherServlet處理. 這里, 我們設置后綴名為 do(*.do) 的所有URL請求都被名為 ideawu 的 DispatcherServlet 的程序處理. 選擇 .do 只是一個習慣,但是你不要選擇 .html! 雖然《Spring in Action》選擇了 .html, 但是那是一種非常糟糕的作法, 特別是你整合 Apache 和 Tomcat 的時候.
  • 配置 CharacterEncodingFilter (filter 標簽), 否則你會發現中文亂碼. 因為我的 jsp 和 html 文件都是 UTF-8 編碼的, 所以我在 param-value 標簽中設置了 UTF-8. 估計你使用的是 GB2312 或者 GBK, 立即轉到 UTF-8 上來吧.
  • 分解配置文件. context-param 標簽指明我們的配置文件還有 /WEB-INF/database.xml 和 /WEB-INF/applicationContext.xml. ContextLoaderListener(listener 標簽) 由此得知配置文件是哪些, 它會將它們載入.

因為我們將 DispatcherServlet 命名為 ideawu, 所以我們在 WEB-INF 目錄下建立一個名為 ideawu-servlet.xml 的文件:

ideawu-servlet.xml:
 1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "
http://www.springframework.org/dtd/spring-beans.dtd"

3
4 beans
5
6 bean id="viewResolver" class="org.springframework.web.servlet.
_view.InternalResourceViewResolver"

7 property name="prefix" value="/WEB-INF/jsp/" />
8 property name="suffix" value=".jsp" />
9 </bean>
10
11 bean id="simpleUrlHandlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"
12 property name="mappings"
13 props
14 prop key="/hello.do"helloController</prop>
15 </props>
16 </property>
17 </bean>
18
19 bean id="helloController" class="com.ideawu.HelloController"
20 <!--
21 <property name="helloManager" ref="helloManager" />
22 --
23 </bean>
24
25 </beans>

它配置了以下功能:

  • 配置 InternalResourceViewResolver, 它是 jsp 渲染模板的處理器. 如果你告訴 InternalResourceViewResolver 處理一個名為 hello 的模板時, 它會渲染 /WEB-INF/jsp/hello.jsp 文件. 把 jsp 文件放到 /WEB-INF/jsp/ 目錄下是被鼓勵的, 這樣可以防止用戶不經過 Controller 直接訪問 jsp 文件從而出錯(有些頑皮的人很喜歡這樣做).
  • 配置 SimpleUrlHandlerMapping, 在上面的配置文件中, /hello.do 的請求將被 helloController 處理. "/hello.do"和"helloController" 是變量, 你可以更改. 但是你注意到了嗎, hello.do 以 .do 作為后綴名. 如果這里(本文的條件下)你 不使用.do 作為后綴名, 就沒有程序來處理這個請求了. 因為 DispatcherServlet 將收到的請求轉交給 SimpleUrlHandlerMapping, DispatcherServlet 收不到的請求, SimpleUrlHandlerMapping 當然也收不到了. 你可以在 props 標簽內配置多個 prop 標簽.
  • 我們將在后面編寫 com.ideawu.HelloController 類.

上面, 我們在 web.xml 文件中告訴 ContextLoaderListener, 我們還有另外兩個配置文件 /WEB-INF/database.xml 和 /WEB-INF/applicationContext.xml.

applicationContext.xml:
 1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "
http://www.springframework.org/dtd/spring-beans.dtd"

3
4 beans
5
6 bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
7 property name="locations"
8 list
9 value/WEB-INF/jdbc.properties</value>
10 </list>
11 </property>
12 </bean>
13
14 </beans>

它配置了以下功能:

  • 讀取 /WEB-INF/jdbc.properties 文件. 你可以在 list 標簽中配置多個 value 標簽.
database.xml:
 1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "
http://www.springframework.org/dtd/spring-beans.dtd"

3
4 beans
5
6 <!-- Remove this if your database setting is fine.
7 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
8 <property name="driverClassName" value="${jdbc.driverClassName}"/>
9 <property name="url" value="${jdbc.url}"/>
10 <property name="username" value="${jdbc.username}"/>
11 <property name="password" value="${jdbc.password}"/>
12 </bean>
13 --
14
15 <!-- Transaction manager for a single JDBC DataSource
16 <bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

17 <property name="dataSource" ref="dataSource"/>
18 </bean>
19 --
20
21 <!--
22 <bean id="attributeManager" class="com.ideawu.core.AttributeManager">
23 <property name="dataSource" ref="dataSource"/>
24 </bean>
25 --
26
27 </beans>

它配置了以下功能(不過,已經注釋掉了):

  • 配置數據庫連接. 類似${jbbc.url}是一種訪問變量的方法. 我們可以從 /WEB-INF/jdbc.properties 中找到這個變量的值. 如果你的數據庫已經配置好, 就將第一個注釋去掉.
jdbc.properties:
1 jdbc.driverClassName=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=UTF-8
3 jdbc.username=test
4 jdbc.password=12345
現在, 我們來編寫 Java 代碼吧.
 1 /***********************************************************
2 * Date: 2006-8-26
3 * File: HelloController.java
4 * Author: ideawu
5 ***********************************************************/
6
7 package com.ideawu;
8
9 import org.springframework.web.servlet.mvc.Controller;
10 import org.springframework.web.servlet.ModelAndView;
11
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 /**
16 * @author ideawu
17 *
18 */
19 public class HelloController implements Controller {
20 /*
21 private HelloManager helloManager;
22
23 public void setHelloManager(HelloManager helloManager) {
24 this.helloManager = helloManager;
25 }
26 */
27
28 public ModelAndView handleRequest(HttpServletRequest request,
29 HttpServletResponse response)throws Exception{
30
31 request.setAttribute("hello_1""你好啊, Spring!");
32 request.setAttribute("hello_2""Hello World!");
33
34 return new ModelAndView("hello");
35 }
36
37 }

return new ModelAndView("hello"); 告訴 InternalResourceViewResolver jsp 模板的名字叫作 hello. request.setAttribute() 設置的對象我們可以在 jsp 文件中使用.

hello.jsp:
 1 <%@ page contentType="text/html; charset=UTF-8" %>
2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"

4 html xmlns="http://www.w3.org/1999/xhtml"
5 head
6 meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
7 titleHello World!</title
8 </head
9 body
10
11 h2${hello_1}</h2
12
13 h2${hello_2}</h2
14
15 </body
16 </html

你可以下載整個 Web 應用程序. 在 Debian Linux, Tomcat 5.5.16, JDK1.5.0 下運行良好. 解壓后得到一個 spring 文件夾, 放到你的 webapps 目錄下, 在瀏覽器中輸入 http://localhost:8080/spring/hello.do 就可以訪問了。

作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗