参数注入
参数注入
路径参数
路径参数即指处理请求的someUrl/{paramId}
,这时的
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@RequestMapping("/pets/{petId}")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}
上面代码把
请求头
Host localhost:8080
Accept text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
可以通过如下方式来获取对应的参数值:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
//...
}
上面的代码,把
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
参数绑定的代码:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
//...
}
即把
请求体
application/x-www-form-urlencoded
编码的内容,提交方式
@Controller
@RequestMapping("/pets")
@SessionAttributes("pet")
public class EditPetForm {
// ...
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
Pet pet = this.clinic.loadPet(petId);
model.addAttribute("pet", pet);
return "petForm";
}
// ...
该注解有两个属性: value、required; application/x-www-form-urlencoded
的内容,处理完的结果放在一个
@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
@SessionAttributes 与@ModelAttribute
该注解用来绑定
@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("pet")
public class EditPetForm {
// ...
}
该注解有两个用法,一个是用于方法上,一个是用于参数上;
-
用于方法上时:通常用来在处理
@RequestMapping 之前,为请求绑定需要从后台查询的model ; -
用于参数上时:用来通过名称对应,把相应名称的值绑定到注解的参数
bean 上;
HttpServletRequest & HttpServletResponse
@Autowired HttpServletRequest request;
注意,
public DeferredResult<String> autologin(
@PathVariable String user_id,//路徑參數,在统一的鉴权的Aspect中完成替换
@RequestParam("requestData") String requestData,//請求數據,
HttpServletResponse response//固定写法,把HttpServletResponse放在最后
)
这样的话就可以在