Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring MVC 入門實作:打造第一個 HelloWorld Web 專案

主題:用 Spring MVC 建一個 HelloWorld Web 專案。
目的:以最小成本親手體驗 Spring MVC 的請求流程。

步驟一:建立工程與引入套件

新建 Web 專案並命名為 SpringMVC,把 Spring MVC 需要的 jar 全部匯入。接著在 src 下新增 spring-mvc.xml,檔名可以自取,但建議一眼就看得出用途。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
       xmlns:mvc="https://www.springframework.org/schema/mvc"
       xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="https://www.springframework.org/schema/context"
       xmlns:tx="https://www.springframework.org/schema/tx"
       xmlns:aop="https://www.springframework.org/schema/aop"
       xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-4.0.xsd
        https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
</beans>

步驟二:在 web.xml 註冊前端控制器

Spring MVC 的入口是 DispatcherServlet,透過 init-param 指定剛剛的設定檔,並用 load-on-startup 讓容器啟動時就完成初始化。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xmlns="https://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">
  <display-name>SpringMVC</display-name>
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <!-- DispatcherServlet 前端控制器 -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

這裡的 *.action 決定了哪些 URL 會走 Spring MVC,你可以換成 *.do 或 /。

步驟三:配置三個核心 Bean

回到 spring-mvc.xml,需要三個角色:HandlerMapping 負責把請求路徑對應到 Controller;InternalResourceViewResolver 負責視圖解析;HelloController 則是真正處理請求的元件。

<!-- 定義請求映射關係,HandlerMapping 是 Spring 核心組件之一 -->
<bean id="handlerMapping"
      class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="mappings">
    <map>
      <entry key="/hello.action">
        <value>helloController</value>
      </entry>
    </map>
  </property>
</bean>

<!-- 註冊 Controller -->
<bean id="helloController" class="controller.HelloController" />

<!-- 視圖解析器,Spring 核心組件之一 -->
<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="WEB-INF/jsp/"/>
  <property name="suffix" value=".jsp"/>
</bean>

步驟四:撰寫 Controller

這個版本的做法是實作 Controller 介面,並在 handleRequest 中回傳 ModelAndView。

package controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
        ModelAndView mv = new ModelAndView("hello");
        System.out.println("處理 hello.action 請求");
        return mv;
    }
}

回傳的 "hello" 會被視圖解析器加上前綴 WEB-INF/jsp/ 與後綴 .jsp,最終導向前往 /WEB-INF/jsp/hello.jsp。

步驟五:新增 JSP 頁面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World</title>
</head>
<body>
  歡迎來到 Spring 的世界!
</body>
</html>

步驟六:啟動並驗證

部署到容器後,拜訪 https://localhost/SpringMVC/hello.action,看到歡迎字樣即代表流程打通。

值得補充的是,SimpleUrlHandlerMapping 與 Controller 介面屬於較早期的寫法。真實專案多半會改用 @Controller 加上 @RequestMapping 的註解方式,並搭配 <mvc:annotation-driven> 啟用註解支援,設定會精簡很多。先把這份最小範例跑通,再遷移到註解寫法,理解會更扎實。

Copyright © Linux教程網 All Rights Reserved