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

SpringMVC 實戰進階:商品修改功能全流程實現與 Controller 返回值模式詳解

     編輯:Java 綜合教學

SpringMVC 實戰進階:商品修改功能全流程實現與 Controller 返回值模式詳解

在掌握基礎查詢後,本文以「商品信息修改」為例,完整演示 SpringMVC 從 Mapper、Service 到 Controller 的分層開發流程,重點解析 Controller 多種返回值類型(ModelAndView、String、void)的使用場景與轉發/重定向機制。

一、業務流程設計

  1. 用戶點擊商品列表「修改」按鈕,攜帶 id 請求 /items/editItems?id=1。
  2. Controller 調用 Service 查詢商品詳情,攜帶數據轉發到編輯頁面 items/editItems.jsp。
  3. 用戶修改表單提交到 /items/editItemsSubmit,Controller 調用 Service 更新數據庫。
  4. 更新成功後,重定向/轉發回商品列表頁 /items/queryItems.action。

二、Mapper 層(MyBatis)

// 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。

三、Service 層

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 層:核心實現與返回值模式解析

@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";
    }
}

五、Controller 返回值類型深度對比

返回類型適用場景核心特性
ModelAndView需同時控制模型數據與視圖,邏輯複雜手動構建 new ModelAndView("viewName", "key", obj),功能最全
String (邏輯視圖名)最常用,配合 @RequestParam/Model 參數視圖解析器拼接前綴後綴;支持 redirect:/forward: 前綴
void自定義響應:AJAX 返回 JSON、文件下載、流輸出注入 HttpServletResponse 手動寫入:response.getWriter().write(json)

六、重定向 vs 轉發 核心差異

  • redirect (重定向):瀏覽器發起新請求 (HTTP 302),地址欄變化,request 域數據丟失,可訪問不同 Controller/項目,防止 F5 重複提交。
  • forward (轉發):服務器內部跳轉,地址欄不變,共享 request 域,僅限同一 Web 應用內,性能略高。

表單提交後必須用 redirect (Post-Redirect-Get 模式),避免用戶刷新頁面重複提交。

七、@RequestMapping 進階用法總結

  1. 類級別 @RequestMapping("/items") + 方法級別 @RequestMapping("/editItems") = 完整路徑 /items/editItems,模塊化管理。
  2. method={RequestMethod.GET, RequestMethod.POST} 限制 HTTP 方法,增強安全性。
  3. @RequestParam(value="id", required=true, defaultValue="1") 綁定請求參數,支持必填校驗與默認值。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved