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

Spring MVC 參數綁定、數據傳遞、轉發與重定向實戰大全

     編輯:Java 綜合教學

Controller 層核心技能:從請求參數到視圖響應的完整鏈路

Spring MVC Controller 處理請求的核心能力包括:參數接收(原生/註解/對象)、數據傳遞、Session 操作、視圖解析(轉發/重定向)。本文通過一個完整的 HelloController 示例,系統演示 11 種常見場景的代碼實現與最佳實踐。

一、參數接收三大方式

1. 原生 HttpServletRequest

@RequestMapping("/test1.do")
public ModelAndView test1(HttpServletRequest req) {
    String userName = req.getParameter("userName");
    String password = req.getParameter("password");
    return new ModelAndView("jsp/hello");
}

2. @RequestParam 註解綁定

@RequestMapping("/test2.do")
public ModelAndView test2(String userName, @RequestParam("password") String pwd) {
    // 參數名與變量名一致可省略 @RequestParam
    return new ModelAndView("jsp/hello");
}

3. 命令對象 / 表單對象自動綁定

@RequestMapping("/test3.do")
public ModelAndView test3(User user) {
    // Spring 自動實例化 User,按名稱匹配請求參數設置屬性
    return new ModelAndView("jsp/hello");
}

User 實體:標準 JavaBean,含 id、userName、password 及 getter/setter。

二、向視圖傳遞數據三大方式

1. ModelAndView 構造器攜帶 Map

@RequestMapping("/test4.do")
public ModelAndView test4(User user) {
    Map<String, Object> data = new HashMap<>();
    data.put("user", user);
    return new ModelAndView("jsp/hello", data); // request.setAttribute
}

2. ModelMap 參數注入

@RequestMapping("/test5.do")
public ModelAndView test5(User user, ModelMap modelMap) {
    modelMap.put("user", user);
    return new ModelAndView("jsp/hello");
}

3. @ModelAttribute 參數/方法級綁定

@RequestMapping("/test6.do")
public ModelAndView test6(@ModelAttribute("user") User user) {
    // 自動將 user 放入 request 屬性鍵 "user"
    return new ModelAndView("jsp/hello");
}
@ModelAttribute("age")
public Integer getAge() { return 22; } // 全局屬性,所有請求可用

三、Session 操作

@RequestMapping("/test7.do")
public ModelAndView test7(HttpServletRequest req) {
    HttpSession session = req.getSession();
    session.setAttribute("salary", 6000.0);
    return new ModelAndView("jsp/hello");
}

或直接在方法簽名聲明 HttpSession session,Spring 自動注入。

四、視圖解析:轉發 vs 重定向

1. 返回 String 邏輯視圖名(默認轉發)

@RequestMapping("/test8.do")
public String test8(User user, ModelMap model) {
    model.addAttribute("user", user);
    return "jsp/hello"; // InternalResourceViewResolver 拼接前綴/後綴
}

2. RedirectView 程式化重定向

@RequestMapping("/test10")
public ModelAndView test10(User user) {
    if ("123".equals(user.getUserName())) {
        return new ModelAndView("jsp/hello"); // 轉發
    } else {
        return new ModelAndView(new RedirectView("test9.do")); // 重定向到 test9
    }
}

3. redirect: 前綴聲明式重定向(推薦)

@RequestMapping("/test11")
public String test11(User user) {
    if ("123".equals(user.getUserName())) {
        return "jsp/hello";
    } else {
        return "redirect:test9.do"; // 瀏覽器發起新請求
    }
}

五、核心差異對比

特性轉發重定向
請求次數1 次2 次(服務器 302 → 瀏覽器新請求)
URL 變化不變變為目標 URL
Request 域共享是否(新請求新 Request)
適用場景同一業務流程內跳轉跨模塊、POST 後防重複提交、登錄檢查失敗
數據傳遞request.setAttributeFlashMap / Session / URL 參數

六、最佳實踐建議

  1. 優先使用 String 返回視圖名 + Model/Map 參數,代碼簡潔。
  2. 表單提交成功後必須重定向(PRG 模式),防止 F5 重複提交。
  3. 重定向攜帶數據用 RedirectAttributes.addFlashAttribute,自動放入 FlashMap,目標請求可讀一次即銷毀。
  4. 避免在 Controller 直接操作 HttpServletResponse 輸出 JSON,改用 @RestController + 返回對象。
  5. @ModelAttribute 方法級用於全局數據(如菜單、用戶信息),參數級用於表單回顯。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved