SpringMVC 數據傳遞靈活多樣,本文匯總後端向前端、前端向後端、RESTful 風格、請求參數綁定等完整代碼範例。
@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}
@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>
@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";
}
@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>
@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>
有名稱綁定:@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 或表單提取,支援必填、默認值。