/items/1 而非 /queryItems.action?id=1。GET 查詢、POST 新增、PUT/PATCH 更新、DELETE 刪除。Accept/Content-Type 協商表示格式,首選 JSON。@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 寫入響應體。為支援 /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>
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。