1. 程式人生 > >三分鐘學會用SpringMVC搭建最小系統(超詳細)_轉載

三分鐘學會用SpringMVC搭建最小系統(超詳細)_轉載

前言

做 Java Web 開發的你,一定聽說過SpringMVC的大名,作為現在運用最廣泛的Java框架,它到目前為止依然保持著強大的活力和廣泛的使用者群。

本文介紹如何用eclipse一步一步搭建SpringMVC的最小系統,所謂最小系統,就是足以使專案在SpringMVC框架下成功跑起來,並且能夠做一些簡單的事情(比如訪問頁面)的系統。

話不多說,讓我們開始吧。所有的原始碼和jar包都會在最後給出。

其他環境:
作業系統:Windos 10
Tomcat : v7.0
JDK : 1.7

正文

1. 新建一個專案

Paste_Image.png

我們用eclipse新建專案,選擇Dynamic Web Project(動態的Web專案)。

點選Next

Paste_Image.png

Project name裡面寫上 springmvc,這就是我們專案的名稱,其他不用改,直接點選Finish 。

Paste_Image.png

OK,專案就建好了。

接下來一定要將專案的字符集改為UTF-8

右鍵專案——properties

Paste_Image.png

改為UTF-8,點選OK。

2. 編寫 web.xml

當我們開啟WebContent/WEB-INF目錄的時候,發現裡面只有一個lib目錄,這是存放各種jar包的地方。我們知道一個web專案必須要有一個web.xml檔案才行。

既然沒有,我們自己寫一個咯。

右鍵WEB-INF——new——file,新建一個web.xml檔案。

點選Finish

將以下內容填進去即可。

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"> <!-- 這是專案的名稱 --> <display-name>springmvc</display-name> </web-app>

這樣就完成了基本的配置,我的意思是說,現在這個專案就已經是一個標準的web專案了。

3. 驗證web專案是否搭建成功

為了驗證到目前為止的正確性,我們在WebContent目錄下面新建一個jsp檔案。

名字就叫index.jsp

Paste_Image.png

內容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <meta charset="UTF-8" /> </head> <body> 恭喜,web專案已經成功搭建! </body> </html>

我們現在就將這個專案部署到Tomcat,來驗證是否可以跑起來。

在專案上右鍵——Debug As——Debug on Server

直接點選Finish

經過一段時間,控制檯開始列印日誌資訊,當我們看到這些資訊的時候,說明Tomcat已經啟動完畢了。

Paste_Image.png

讓我們開啟瀏覽器,在位址列輸入以下資訊

http://localhost:8088/springmvc/index.jsp

我電腦上Tomcat配置的埠號是8088,具體情況視你自己的Tomcat決定,可能是8080等。

Paste_Image.png

可見,能夠成功訪問頁面了,這說明我們到目前為止的操作是正確的。

3. 整合SpringMVC

我們在web.xml檔案裡面新增下面的配置
3.1 配置監聽器

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener>

3.2 配置過濾器,解決POST亂碼問題

<filter>
    <filter-name>encoding</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> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

3.3 配置SpringMVC分發器,攔截所有請求

<servlet>
    <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>namespace</param-name> <param-value>dispatcher-servlet</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>

在這個配置中,我們規定了 DispatcherServlet 的關聯 XML 檔名稱叫做 dispatcher-servlet。

注意,這裡的路徑是相對於web.xml來說的,也就是說,這個檔案也在WEB-INF的根目錄下。

所以,我們需要在WEB-INF的根目錄下新建一個dispatcher-servlet.xml檔案。

Paste_Image.png

至此,web.xml檔案的編寫就告一段落了。

3.4 編寫dispatcher-servlet.xml
dispatcher-servlet.xml 的作用就是配置SpringMVC分發器。

配置如下:

<?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" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-- 開啟註解模式驅動 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 掃包 --> <context:component-scan base-package="com.springmvc.*"></context:component-scan> <!-- 靜態資源過濾 --> <mvc:resources location="/resources/" mapping="/resources/**"/> <!-- 檢視渲染 jsp/freemaker/velocity--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 制定頁面存放的路徑 --> <property name="prefix" value="/WEB-INF/pages"></property> <!-- 檔案的字尾 --> <property name="suffix" value=".jsp"></property> </bean> </beans>

根據配置,有三個需要注意的地方。

  1. 它會掃描 com.springmvc 包下所有的Java類,但凡是遇到有註解的,比如@Controller , @Service , @Autowired ,就會將它們加入到Spring的bean工廠裡面去。

  2. 所有的靜態資原始檔,比如說 js , css , images 都需要放在/resources目錄下,這個目錄現在我們還沒有建。

  3. 所有的展示頁面,比如jsp檔案,都需要放置在/WEB-INF/pages目錄下,這個目錄現在我們也沒有建。

OK,我們把對應的目錄加上。

首先是Java檔案的目錄。

Paste_Image.png

我們在這個地方右鍵,新建一個 com 包,再在裡面建一個 springmvc 包,或者用 . 的方式一起建。

Paste_Image.png

點選Finish

Paste_Image.png

根據SpringMVC的分層,我們在springmvc 包下面建三個包,分別是controller , service , dao

Paste_Image.png

這樣的話, 當我們專案一旦啟動,springmvc就會掃描這三個包,將裡面但凡是有註解的類都提取起來,放進Spring容器(或者說Spring的bean工廠),藉由Spring容器來統一管理。這也就是你從來沒有去new一個Controller的原因。

接下來,我們來建靜態資源的目錄。

在WebContent目錄下新建一個resources資料夾。

然後順便把js,css,img的資料夾都建一下,這裡就存放我們的靜態資原始檔。

Paste_Image.png

最後,我們在WEB-INF目錄下建一個pages資料夾,作為展示頁面的存放目錄。

Paste_Image.png

將之前的index.jsp拷貝進來。

Paste_Image.png

這樣就配置的差不多了。

5. 導包和驗證

我們將jar包放到lib目錄:

Paste_Image.png

然後啟動專案,驗證一下到目前為止的構建是否正確。

開啟Servers檢視,點選如影象是甲蟲一樣的圖示。

Paste_Image.png

發現報錯了,錯誤資訊如下:

Paste_Image.png

錯誤:
Could not open ServletContext resource [/WEB-INF/applicationContext.xml]

它說我們在WEB-INF下面少了一個applicationContext.xml 這個檔案,原來,我們少了對SpringBean工廠的配置,它的意思就是說,我們要規定一下,在Spring容器啟動的時候,需要自動載入哪些東西?

於是,我們把 applicationContext.xml 加上。
Paste_Image.png

<?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd "> </beans>

裡面我們啥也不配置,再次啟動Tomcat。

Paste_Image.png

這回不報錯了。

5. 配置ViewController

我們知道,WEB-INF目錄下的任何資源都是無法直接通過瀏覽器的url地址去訪問的,保證了安全性。這也是我們為什麼把頁面都放在該目錄下的原因。

為了有所區分,我們還單獨建立了一個pages資料夾,將這些頁面儲存起來。

Paste_Image.png

現在,為了訪問這個頁面,我們需要用到SpringMVC的頁面跳轉機制。

我們在Controller包下新建一個ViewController

Paste_Image.png

點選Finish

Paste_Image.png

ViewController 程式碼:

package com.springmvc.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class ViewController { @RequestMapping("/view") public ModelAndView view(HttpServletRequest request){ String path = request.getParameter("path") + ""; ModelAndView mav = new ModelAndView(); mav.setViewName(path); return mav; } }

我只需要將想要訪問的頁面放在path裡面,通過url傳進來就行了。

因為添加了java類,因此我們重新啟動Tomcat。

啟動完成後,在位址列輸入:
http://localhost:8088/springmvc/view?path=index

結果:

Paste_Image.png

沒關係,我們看他報什麼錯。

message /springmvc/WEB-INF/pagesindex.jsp

pagesindex.jsp是什麼鬼??

原來,在dispatcher-servlet.xml中,我們少寫了一個 "/"

Paste_Image.png

添上去就行了。

Paste_Image.png

儲存後,因為修改了XML配置檔案,因此我們還是需要重新啟動Tomcat。

啟動完成後,繼續!

Paste_Image.png

成功了。

6. 引入靜態資源

比如,我在resources/img目錄下放了一張圖片,怎麼引入到index.jsp呢?

Paste_Image.png

background : url(http://localhost:8088/springmvc/resources/img/bg.jpg); background-size : 100% 100%;

的確,這是一種方式。可是,它有一個缺點就是根路徑寫死了,我們肯定不希望這樣的。

其實,我們可以在viewController裡面拿到專案根路徑,然後傳遞到jsp頁面就OK了。

Paste_Image.png

我們把除錯資訊 “恭喜,web專案已經成功搭建!” 刪掉。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <meta charset="UTF-8" /> </head> <style> body { background : url(${contextPath}/resources/img/bg.jpg); background-size : 100% 100%; } </style> <body> </body> </html>

${contextPath} 可以取到Controller傳過來的contextPath值。

成功了!


作者:剽悍一小兔
連結:https://www.imooc.com/article/22649
來源:慕課網
本文原創釋出於慕課網 ,轉載請註明出處,謝謝合作