spring-web + spring-webmvc (版本一致,如 3.2.7.RELEASE)。<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:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern> <!-- 推薦 /,攔截所有請求;靜態資源需額外配置 -->
</servlet-mapping>
關鍵點:
url-pattern 用 / 而非 /*,避免 JSP 被攔截導致 404。load-on-startup > 0 實現容器啟動時初始化。<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:mvc="https://www.springframework.org/schema/mvc"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="...spring-mvc.xsd ...spring-context.xsd ...spring-beans.xsd">
<!-- 1. 掃描 Controller 包 -->
<context:component-scan base-package="com.xx.controller"/>
<!-- 2. 啟用註解驅動 (請求映射、參數綁定、返回值處理) -->
<mvc:annotation-driven/>
<!-- 3. 靜態資源釋放 (關鍵!) -->
<mvc:resources mapping="/resources/**" location="/resources/"/>
<!-- 4. 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping("/test")
public ModelAndView test() {
return new ModelAndView("hello"); // 解析為 /WEB-INF/jsp/hello.jsp
}
@RequestMapping(value="/xiake", method=RequestMethod.GET)
public ModelAndView xiakeGet() { ... }
@RequestMapping(value="/xiake", method=RequestMethod.POST)
public ModelAndView xiakePost(HttpServletRequest request) { ... }
}
| 模式 | 匹配示例 | 說明 |
|---|---|---|
/test | /test | 精確匹配 |
{"/t1","/t2"} | /t1, /t2 | 多路徑映射同一方法 |
/test/* | /test/a, /test/b | 一級通配 |
/test/** | /test/a/b/c | 多級通配 |
/test/? | /test/a | 單字符通配 |
/test/?? | /test/ab | 雙字符通配 |
@RequestMapping("/param")
public String param(
// 1. 基本類型自動綁定 (請求參數名 = 方法參數名)
String username, int age,
// 2. POJO 自動封裝 (含級聯屬性 user.address.city)
User user,
// 3. 數組綁定 (不可用 List)
String[] hobbies,
// 4. @RequestParam 定制
@RequestParam(value="nick", required=false, defaultValue="guest") String nickname,
// 5. @PathVariable RESTful 路徑變量
@PathVariable("uid") Long userId,
@PathVariable String token
) { ... }
InternalResourceViewResolver 將邏輯視圖名 hello 拼接為物理路徑 /WEB-INF/jsp/hello.jsp,再轉發渲染。
@ResponseBody:直接將返回對象序列化為 JSON/XML 寫入 Response Body。@RequestBody:將 Request Body 反序列化為對象參數。HttpMessageConverter (Jackson/Fastjson) 實現自動轉換。