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

Spring MVC RESTful 風格開發:@PathVariable 映射、DispatcherServlet 配置與靜態資源釋放

     編輯:Java 綜合教學

RESTful 架構風格核心原則

  • 資源導向:URL 僅標識資源(名詞),不包含動詞。/items/1 而非 /queryItems.action?id=1。
  • HTTP 勞動語義:GET 查詢、POST 新增、PUT/PATCH 更新、DELETE 刪除。
  • 內容協商:通過 Accept/Content-Type 協商表示格式,首選 JSON。

Controller 實現:RESTful 端點設計

@Controller
@RequestMapping("/items")
public class ItemsController {

    @Autowired private ItemsService itemsService;

    // 查詢單個資源:GET /items/{id}
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer itemsId) throws Exception {
        return itemsService.findItemsById(itemsId);
    }

    // 新增資源:POST /items
    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody ItemsCustom itemsAdd(@RequestBody ItemsCustom items) throws Exception {
        itemsService.addItems(items);
        return items;
    }

    // 更新資源:PUT /items/{id}
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public @ResponseBody ItemsCustom itemsUpdate(@PathVariable("id") Integer id, @RequestBody ItemsCustom items) throws Exception {
        items.setId(id);
        itemsService.updateItems(items);
        return items;
    }

    // 刪除資源:DELETE /items/{id}
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public @ResponseBody void itemsDelete(@PathVariable("id") Integer id) throws Exception {
        itemsService.deleteItems(id);
    }
}

關鍵註解:

  • @PathVariable("id") 將 URI 模板變量 {id} 綁定到方法參數。若變量名與參數名一致,可省略 ("id")。
  • @RequestBody 將請求體 JSON 反序列化為對象(需配置 MappingJacksonHttpMessageConverter)。
  • @ResponseBody 將返回對象序列化為 JSON 寫入響應體。

DispatcherServlet 配置:REST 風格 URL 的關鍵

為支援 /items/1 這類無後綴 URL,url-pattern 必須設為 / 而非 *.action:

<servlet>
    <servlet-name>springmvc_rest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springmvc.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>springmvc_rest</servlet-name>
    <url-pattern>/</url-pattern> <!-- 關鍵:攔截所有請求 -->
</servlet-mapping>

靜態資源釋放:避免 404 陷阱

url-pattern:/ 會攔截 .js、.css、.png 等靜態資源請求,導致 404。需在 springmvc.xml 配置 <mvc:resources> 釋放:

<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/images/**" location="/images/" />
<!-- 或通配所有靜態資源 -->
<mvc:resources mapping="/**" location="/static/" />

原理:ResourceHttpRequestHandler 在 HandlerMapping 鏈中優先匹配靜態資源路徑,直接讀取 classpath/WebRoot 返回,不進入 Controller。

測試驗證

訪問 GET https://localhost:8080/items/1 返回 JSON:

{
  "id": 1,
  "name": "手機",
  "price": 4999,
  "detail": "最新款旗艦機"
}

瀏覽器 Network 面板可見 Content-Type: application/json;charset=UTF-8。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved