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

SpringMVC 參數傳遞與數據綁定完整實戰指南

     編輯:Java 相關知識

SpringMVC 參數傳遞與數據綁定完整實戰指南

SpringMVC 數據傳遞靈活多樣,本文匯總後端向前端、前端向後端、RESTful 風格、請求參數綁定等完整代碼範例。

一、後端向前端傳值

1. ModelAndView

@Controller
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping("/sub")
    public ModelAndView submit(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("ok", "hello"); // 值為 Object 類型,任意物件
        mv.setViewName("success");   // 跳轉 success.jsp
        return mv;
    }
}

JSP 取值:${requestScope.ok} 或 ${ok}

2. 自動綁定表單對象

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/get")
    public ModelAndView user(User user) { // 自動綁定表單字段
        ModelAndView mv = new ModelAndView();
        mv.addObject("ok", user.getUsername() + "--" + user.getPassword());
        mv.setViewName("success");
        return mv;
    }
}

前端表單:<form action="user/get" method="post"> ... </form>

3. Map/Model/ModelMap 統一入參

@RequestMapping("/map")
public String ok(Map map, Model model, ModelMap modelMap, User user) {
    map.put("ok1", user);
    model.addAttribute("ok2", user);
    modelMap.addAttribute("ok3", user);
    return "show";
}

二、前端向後端傳值

1. @PathVariable 路徑變量 (RESTful)

@RequestMapping(value="/ant/{username}/topic/{topic}", method=RequestMethod.GET)
public ModelAndView ant(@PathVariable("username") String username,
                        @PathVariable("topic") String topic) {
    System.out.println(username + " - " + topic);
    return new ModelAndView();
}

前端連結:<a href="hello/ant/Tom/topic/Cat">ant</a>

2. 正則限制路徑變量

@RequestMapping("/regex/{number:\\d+}-{tel:\\d+}")
public ModelAndView regex(@PathVariable("number") int number,
                          @PathVariable("tel") String tel) {
    System.out.println(number + " - " + tel);
    return new ModelAndView();
}

前端連結:<a href="hello/regex/100-111">regex</a>

3. @RequestParam 請求參數

有名稱綁定:@RequestParam(value="username") String username → ?username=Tom

無名稱綁定:@RequestParam String password, @RequestParam String username → ?username=Tom&password=111 (按參數名自動匹配)

核心總結

  • ModelAndView:攜帶數據+視圖跳轉。
  • Map/Model/ModelMap:僅攜帶數據,返回視圖名。
  • @PathVariable:RESTful 風格,從 URL 路徑提取。
  • @RequestParam:從 Query String 或表單提取,支援必填、默認值。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved