傳統 Spring MVC 專案常見 *.do 後綴的請求路徑,不僅不美觀,也不符合 REST 風格規範。本文詳細講解如何通過 web.xml 與 spring-mvc.xml 配置,實現無後綴的 REST 風格 URL(如 /article/list、/article/details/1),並解決隨之而來的靜態資源(JS、CSS、圖片)攔截失效問題。
關鍵點:<url-pattern>/</url-pattern> 而非 *.do,使 DispatcherServlet 成為唯一前端控制器,攔截所有進入應用的請求(含靜態資源)。
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context:component-scan base-package="com"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
@Controller
@RequestMapping("/article")
public class ArticleController {
@RequestMapping("/list")
public String list(Model model) {
return "article/list"; // 對應 /WEB-INF/jsp/article/list.jsp
}
@RequestMapping("/details/{id}")
public ModelAndView details(@PathVariable("id") int id) {
ModelAndView mav = new ModelAndView("article/details");
if (id == 1) mav.addObject("article", new Article("文章一", "內容一"));
else if (id == 2) mav.addObject("article", new Article("文章二", "內容二"));
return mav;
}
}
關鍵註解:
@PathVariable:從 URL 路徑中提取變量(如 /details/1 中的 1)。@RequestParam:從請求參數中獲取值(如 ?id=1)。list.jsp - 列表頁,構建 REST 風格鏈接:
<a href="${pageContext.request.contextPath}/article/details/1">文章一</a>
<a href="${pageContext.request.contextPath}/article/details/2">文章二</a>
details.jsp - 詳情頁,展示模型數據:
<p>${article.title}</p>
<p>${article.content}</p>
因 url-pattern:/ 攔截所有請求,導致 <img src="...">、<link href="..."> 等靜態資源請求也進入 DispatcherServlet,找不到對應 Controller 而 404。解決方案:在 spring-mvc.xml 配置 <mvc:resources> 映射靜態資源路徑,繞過 Controller 處理。
<mvc:resources mapping="/resources/**" location="/images/"/> <mvc:resources mapping="/resources2/**" location="/css/"/>
頁面引用方式:
<img src="${pageContext.request.contextPath}/resources/logo.png" />
<link href="${pageContext.request.contextPath}/resources2/style.css" rel="stylesheet" />
https://localhost:8080/SpringMvc03/article/list → 顯示文章列表,URL 無 .do 後綴。/article/details/1,地址欄顯示乾淨 REST 風格路徑。

web.xml 用 / + Controller 用 @PathVariable。<mvc:resources>,否則會被攔截器吞噬。/static, /public, /resources, /META-INF/resources),無需額外配置。