在掌握基礎查詢後,本文以「商品信息修改」為例,完整演示 SpringMVC 從 Mapper、Service 到 Controller 的分層開發流程,重點解析 Controller 多種返回值類型(ModelAndView、String、void)的使用場景與轉發/重定向機制。
id 請求 /items/editItems?id=1。items/editItems.jsp。/items/editItemsSubmit,Controller 調用 Service 更新數據庫。/items/queryItems.action。// ItemsMapper.xml (或逆向工程生成)
<select id="selectByPrimaryKey" resultType="Items">
SELECT * FROM items WHERE id = #{id}
</select>
<update id="updateByPrimaryKeyWithBLOBs" parameterType="Items">
UPDATE items SET name=#{name}, price=#{price}, detail=#{detail}, ... WHERE id=#{id}
</update>
關鍵:updateByPrimaryKeyWithBLOBs 包含大文本字段更新,要求傳入對象必須含 id。
public interface ItemsService {
ItemsCustom findItemsById(Integer id) throws Exception;
void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception;
}
@Service
public class ItemsServiceImpl implements ItemsService {
@Autowired ItemsMapper itemsMapper;
public ItemsCustom findItemsById(Integer id) {
Items items = itemsMapper.selectByPrimaryKey(id);
ItemsCustom custom = new ItemsCustom();
BeanUtils.copyProperties(items, custom); // 屬性拷貝
return custom;
}
@Transactional
public void updateItems(Integer id, ItemsCustom custom) {
if (id == null) throw new IllegalArgumentException("ID不能為空");
custom.setId(id); // 確保 ID 回填
itemsMapper.updateByPrimaryKeyWithBLOBs(custom);
}
}
@Controller
@RequestMapping("/items") // 類級別映射,窄化請求路徑
public class ItemController {
@Autowired ItemsService itemsService;
// 1. 進入編輯頁 (GET/POST 均支持)
@RequestMapping(value="/editItems", method={RequestMethod.GET, RequestMethod.POST})
public String editItems(Model model,
@RequestParam(value="id", required=true) Integer itemsId) {
ItemsCustom custom = itemsService.findItemsById(itemsId);
model.addAttribute("itemsCustom", custom); // 相當於 ModelAndView.addObject
return "items/editItems"; // 邏輯視圖名:前綴 + editItems + 後綴
}
// 2. 提交修改
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(HttpServletRequest request, Integer id, ItemsCustom itemsCustom) {
itemsService.updateItems(id, itemsCustom);
// 方案 A: 重定向 (推薦,防止表單重複提交)
return "redirect:queryItems.action";
// 方案 B: 轉發 (地址欄不變,共享 request 域)
// return "forward:queryItems.action";
// 方案 C: 返回邏輯視圖名 (需配置對應 JSP)
// return "success";
}
}
| 返回類型 | 適用場景 | 核心特性 |
|---|---|---|
ModelAndView | 需同時控制模型數據與視圖,邏輯複雜 | 手動構建 new ModelAndView("viewName", "key", obj),功能最全 |
String (邏輯視圖名) | 最常用,配合 @RequestParam/Model 參數 | 視圖解析器拼接前綴後綴;支持 redirect:/forward: 前綴 |
void | 自定義響應:AJAX 返回 JSON、文件下載、流輸出 | 注入 HttpServletResponse 手動寫入:response.getWriter().write(json) |
表單提交後必須用 redirect (Post-Redirect-Get 模式),避免用戶刷新頁面重複提交。
@RequestMapping("/items") + 方法級別 @RequestMapping("/editItems") = 完整路徑 /items/editItems,模塊化管理。method={RequestMethod.GET, RequestMethod.POST} 限制 HTTP 方法,增強安全性。@RequestParam(value="id", required=true, defaultValue="1") 綁定請求參數,支持必填校驗與默認值。