首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring MVC 註解開發入門:從架構原理到登入實戰

     編輯:Java 綜合教學

Spring MVC 註解開發入門:從架構原理到登入實戰

Spring MVC 憑藉 REST 風格支援、豐富註解、靈活方法簽名、強大型別轉換與驗證體系,成為 Java Web 開發主流框架。本文先梳理架構圖與請求處理流程,再以「簡單登入」為例,完整示範註解式開發:環境搭建、轉發與重導向兩種頁面跳轉方式、參數綁定、異常處理雛形。

一、Spring MVC 核心優勢

  • 原生支援 RESTful URL
  • 全註解驅動,零 XML 配置 Controller
  • 內建 HttpMessageConverter 自動處理 JSON/XML
  • 與資料綁定、格式化、JSR-303 驗證無縫整合
  • 靜態資源處理、異步請求、檔案上傳開箱即用

二、架構與執行流程

Spring MVC 架構圖

  1. 請求到達 DispatcherServlet(前端控制器)。
  2. HandlerMapping 依 URL 尋找對應 Handler(Controller 方法)。
  3. HandlerAdapter 執行 Handler,完成參數綁定、業務邏輯、返回 ModelAndView/String/void。
  4. ViewResolver 解析邏輯視圖名為實際 View(JSP/FreeMarker/Thymeleaf)。
  5. View 渲染 Model 資料,輸出響應。

三、專案結構與關鍵配置

src
├── main
│   ├── java
│   │   └── cn.zhang.controller.MyController
│   ├── resources
│   │   └── applicationContext.xml
│   └── webapp
│       ├── WEB-INF
│       │   ├── web.xml
│       │   └── jsp
│       │       ├── index.jsp
│       │       ├── hello.jsp
│       │       └── error.jsp
│       └── index.jsp (welcome-file)

web.xml

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

applicationContext.xml

<context:component-scan base-package="cn.zhang.controller" />
<mvc:annotation-driven />

四、登入功能實作:轉發

index.jsp(登入頁)

<form action="frist.do" method="post">
    用戶名: <input type="text" name="name" />
    年齡: <input type="text" name="age" />
    <input type="submit" value="提交" />
</form>

MyController.java

@Controller
public class MyController {
    @RequestMapping(value="/frist.do", produces="text/html;charset=utf-8", method=RequestMethod.POST)
    public String frist(Model model, String name, int age) {
        model.addAttribute("name", name);
        model.addAttribute("age", age);
        return "forward:/hello.jsp"; // 伺服器內部轉發
    }
}

hello.jsp(成功頁)

歡迎您<br/>
姓名: ${name}<br/>
年齡: ${age}

error.jsp(失敗頁)

這是錯誤頁面

五、登入功能實作:重導向

修改 Controller,引入兩次重導向:

@Controller
public class MyController {
    @RequestMapping("/frist.do")
    public String frist() {
        return "redirect:hello.do"; // 302 到 hello.do
    }

    @RequestMapping("/hello.do")
    public String hello(Model model, String name, int age) {
        model.addAttribute("name", name);
        model.addAttribute("age", age);
        if ("1".equals(name) && age == 1)
            return "redirect:/hello.jsp"; // 重導向到實體 JSP
        else
            return "redirect:/error.jsp";
    }
}

差異:forward 保持請求屬性、地址列不變;redirect 發起新請求、地址列更新、請求屬性丟失(需用 Session/Flash Attribute 傳遞)。

六、效果展示

輸入頁面

登入成功

登入失敗

七、延伸學習建議

  1. 掌握 @ModelAttribute、@SessionAttributes 跨請求共享資料。
  2. 整合 Validator 實現表單驗證(@Valid + BindingResult)。
  3. 使用 @ExceptionHandler、@ControllerAdvice 統一異常處理。
  4. 嘗試 RestController 開發純 API 服務,配合 ResponseEntity 精準控制 HTTP 狀態碼。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved