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

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

springmvc+mybatis dubbo+zookeeper restful redis分布式緩存 kafka

前言

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

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

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

正文

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類,但凡是遇到有註解的,[email protected] , @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;@Controllerpublic 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了。

技術分享

我們把調試信息 “恭喜,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>

更多詳細源碼參考來源:源碼來源請點擊這裏 歡迎大家一起學習研究相關技術,源碼獲取請加求求(企鵝):2042849237


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