天天看點

從 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。

後 記

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