@RequestMapping注解
RequestMaping是用于處理請求地址映射的注解,可作用于類或方法上纤房。作用于類上時(shí)棍辕,表示該類中所有方法請求響應(yīng)的地址均以該地址為父路徑。
該注解接口中定義了7個(gè)屬性
public interface RequestMapping extends Annotation {
// 指定映射的名稱
public abstract String name();
// 指定請求路徑的地址
public abstract String[] value();
// 指定請求的方式席函,是一個(gè)RequsetMethod數(shù)組铐望,可以配置多個(gè)方法
public abstract RequestMethod[] method();
// 指定參數(shù)的類型
public abstract String[] params();
// 指定請求的header值
public abstract String[] headers();
// 指定數(shù)據(jù)請求的格式
public abstract String[] consumes();
// 指定返回的內(nèi)容類型
public abstract String[] produces();
}
默認(rèn)@RequestMapping("/xxx/xxx")
即指定value=/xxx/xxx
指定請求方式為Post@RequestMapping(value = "/xxx/xxx", method = RequestMethod.POST)
@PathVariable注解
使用@PathVariable來接收request請求地址中的動態(tài)參數(shù),參數(shù)值需要在url進(jìn)行占位茂附,當(dāng)方法參數(shù)名和請求地址中變量名不一致時(shí)正蛙,需要指定變量名@PathVariable(value = "page", defaultValue = "page")
即value值為page,如果本次請求沒有攜帶這個(gè)參數(shù)何之,或者參數(shù)為空跟畅,那么就會啟用默認(rèn)值
@RequestMapping("/{page}")
public String showPage(@PathVariable String page) {
return page;
}
@RequestParam注解
使用@RequestParam接收前端參數(shù)比較方便,而當(dāng)請求參數(shù)不存在時(shí)會有異常發(fā)生,可以通過設(shè)置屬性required=false解決@RequestParam(value="username", required=false)
/**
* url = "localhost:8080/xx?username=${username}&password=${password}"
*/
@RequestMapping("/addUser")
public String addUser(@RequestParam("username") String username,@RequestParam("password") String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "/index";
}
SpringMVC中Controller層獲取請求參數(shù)的幾種方式
- 直接把表單的參數(shù)寫在Controller相應(yīng)的方法的形參中溶推,適用于get方式提交徊件,不適用于post方式提交
- 通過HttpServletRequest接收,post方式和get方式都可以
- 通過一個(gè)pojo對象來接收蒜危,post方式和get方式都可以
- 使用@ModelAttribute注解獲取post請求的form表單數(shù)據(jù)
- 使用@PathVariable注解獲取路徑中的參數(shù)
- 使用@RequestParam注解綁定請求參數(shù)到方法入?yún)?/li>