從 Spring Boot到 Spring MVC(註解方式)


概述

在前文《從SpringBoot到SpringMVC(非註解方式)》之中,我們遠離了 Spring Boot的開箱即用與自動配置的便利性後,迴歸到了淳樸的 Spring MVC開發時代,但是以非註解的方式來給出的,而本文則以註解方式再度講述一遍。

注: 本文首發於 My Personal Blog:CodeSheep·程序羊,歡迎光臨 小站


Spring MVC架構模式

一個典型的Spring MVC請求流程如圖所示,詳細分爲12個步驟:

    1. 用戶發起請求,由前端控制器DispatcherServlet處理
    1. 前端控制器通過處理器映射器查找hander,可以根據XML或者註解去找
    1. 處理器映射器返回執行鏈
    1. 前端控制器請求處理器適配器來執行hander
    1. 處理器適配器來執行handler
    1. 處理業務完成後,會給處理器適配器返回ModeAndView對象,其中有視圖名稱,模型數據
    1. 處理器適配器將視圖名稱和模型數據返回到前端控制器
    1. 前端控制器通過視圖解析器來對視圖進行解析
    1. 視圖解析器返回真正的視圖給前端控制器
    1. 前端控制器通過返回的視圖和數據進行渲染
    1. 返回渲染完成的視圖
    1. 將最終的視圖返回給用戶,產生響應

整個過程清晰明瞭,下面我們將結合實際實驗來理解這整個過程。


Spring MVC項目搭建

實驗環境如下:

  • IntelliJ IDEA 2018.1 (Ultimate Edition)
  • SpringMVC 4.3.9.RELEASE
  • Maven 3.3.9

這裏我是用IDEA來搭建的基於Maven的SpringMVC項目,搭建過程不再贅述,各種點擊並且下一步,最終創建好的項目架構如下:


添加前端控制器配置

使用了SpringMVC,則所有的請求都應該交由SpingMVC來管理,即要將所有符合條件的請求攔截到SpringMVC的專有Servlet上。

爲此我們需要在 web.xml 中添加SpringMVC的前端控制器DispatcherServlet:

    <!--springmvc前端控制器-->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc-dispatcher.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

該配置說明所有符合.action的url,都交由mvc-dispatcher這個Servlet來進行處理


編寫Spring MVC核心XML配置文件

從上一步的配置可以看到,我們定義的mvc-dispatcher Servlet依賴於配置文件 mvc-dispatcher.xml,在本步驟中我們需要在其中添加如下的配置

  • 添加註解的處理器適配器和處理器映射器

方式一:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

方式二:

<mvc:annotation-driven></mvc:annotation-driven>

編寫控制器

由於使用了註解的處理器映射器和處理器適配器,所以不需要在XML中配置任何信息,也不需要實現任何接口,只需要添加相應註解即可。

@Controller
public class TestController {

    private StudentService studentService = new StudentService();

    @RequestMapping("/queryStudentsList")
    public ModelAndView handleRequest( ) throws Exception {
        List<Student> studentList = studentService.queryStudents();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("studentList",studentList);
        modelAndView.setViewName("/WEB-INF/views/studentList.jsp");
        return modelAndView;
    }
}

class StudentService {
    public List<Student> queryStudents() {
        List<Student> studentList = new ArrayList<Student>();

        Student hansonwang = new Student();
        hansonwang.setName("hansonwang99");
        hansonwang.setID("123456");

        Student codesheep = new Student();
        codesheep.setName("codesheep");
        codesheep.setID("654321");

        studentList.add(hansonwang);
        studentList.add(codesheep);

        return studentList;
    }
}

爲了讓註解的處理器映射器和處理器適配器找到註解的Controllor,有兩種配置方式:

方式一:在xml中聲明Controllor對應的bean

<bean class="cn.codesheep.controller.TestController" />

方式二:使用掃描配置,對某一個包下的所有類進行掃描,找出所有使用@Controllor註解的Handler控制器類

<context:component-scan base-package="cn.codesheep.controller"></context:component-scan>

編寫視圖文件

這裏的視圖文件是一個jsp文件,路徑爲:/WEB-INF/views/studentList.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
<head>
    <title>學生名單</title>
</head>
<body>
    <h3>學生列表</h3>
    <table width="300px;" border=1>
        <tr>
            <td>姓名</td>
            <td>學號</td>
        </tr>
        <c:forEach items="${studentList}" var="student" >
            <tr>
                <td>${student.name}</td>
                <td>${student.ID}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

實驗測試

啓動Tomcat服務器,然後瀏覽器輸入:

http://localhost:8080/queryStudentsList.action

數據渲染OK。


後 記

由於能力有限,若有錯誤或者不當之處,還請大家批評指正,一起學習交流!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章