Spring MVC 3.1+ 全面支援註解式開發,極大簡化 Controller 編寫。本文精選 5 大高頻場景:散亂參數自動綁定、物件/Map/泛型參數傳遞、路徑變數提取、多種回傳值類型處理、重導向與轉發,附完整代碼與配置片段,可直接套用至專案。
<!-- applicationContext.xml -->
<context:component-scan base-package="cn.happy.*" />
<mvc:annotation-driven />
<!-- 視圖解析器:前綴 + 後綴 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
@Controller
@RequestMapping("/hr")
public class MyController {
@RequestMapping("/hello.do")
public String show(String name, Model model) { // 表單 name="name" 自動綁定
model.addAttribute("msg", name + " 展示頁面");
return "happy"; // 經視圖解析器 → /WEB-INF/jsp/happy.jsp
}
@RequestMapping(value="/list.do", method=RequestMethod.POST)
public String list(Model model,
@RequestParam(value="uname", required=false) String name) { // 前端參數 uname
return "happy";
}
}
@RequestMapping(value="/list.do", method=RequestMethod.POST)
public String list(Model model, UserInfo info) {
// 前端 name="uname" → info.uname
// 巢狀物件:name="radd.add" → info.radd.add
// 集合:name="booklist[0].bookname" → info.booklist.get(0).bookname
model.addAttribute("uname", info.getUname());
return "index";
}
@Controller
public class HandleReturn {
@RequestMapping("/{rname}/{age}/first.do")
public String handlereturn(Model model,
@PathVariable("rname") String name, // 路徑變數 rname
@PathVariable int age) { // 同名可省略 value
model.addAttribute("name", name);
model.addAttribute("age", age);
return "handle";
}
}
// 請求:/tom/25/first.do → name=tom, age=25
@RequestMapping("/ajax.do")
public void handleAjax(HttpServletResponse response) throws Exception {
Map<String, UserInfo> map = ...;
String json = JSON.toJSONString(map); // Fastjson
response.setCharacterEncoding("utf-8");
response.getWriter().write(json);
}
前端 AJAX:success: function(data) { var obj = eval('('+data+')'); ... }
@RequestMapping("/num.do")
@ResponseBody
public Object number() { return 1; }
@RequestMapping(value="/nums.do", produces="text/html;charset=utf-8")
@ResponseBody
public Object numberS() { return "漢字"; }
@RequestMapping("/third.do")
@ResponseBody
public Object doThird() {
UserInfo info = new UserInfo();
info.setAge(12); info.setName("Happy");
return info; // 自動轉 JSON
}
前端:$.ajax({url:'nums.do', success:function(data){alert(data)}})
@RequestMapping("/ajax.do")
@ResponseBody
public String handleAjax(HttpServletResponse response) throws Exception {
// ... 組裝 jsonString
return jsonString;
}
@Controller
public class Dispatchreturn {
@RequestMapping("add.do")
public String add() { return "redirect:dolist.do"; } // 相對路徑
@RequestMapping("dolist.do")
public String list() { return "redirect:/list.jsp"; } // 絕對路徑(以 / 開頭)
}
注意:redirect: 觸發瀏覽器 302,地址列變化;forward: 伺服器內部轉發,地址列不變。
| 需求 | 關鍵註解/技巧 |
|---|---|
| 參數名不一致 | @RequestParam("前端名") String 後端名 |
| 綁定複雜物件 | 直接宣告實體類參數,遵循 name="prop.nestedProp" 命名 |
| REST 路徑變數 | @PathVariable("路徑佔位符") |
| 回傳 JSON | @ResponseBody + 回傳 Object/String/Map/List |
| 指定編碼 | @RequestMapping(produces="text/html;charset=utf-8") |
| 重導向 | return "redirect:目標URL" |
| 轉發 | return "forward:目標URL" |