SpringMVC--RequestMapping
一、RequestMapping映射URL
1)RequestMapping注解指定控制器能处理哪些URL请求,可用于类定义和方法定义处。
2)RequestMapping常用属性有value、params、method、headers,表示请求URL地址、请求方法、请求参数及请求头。他们之间是与的关系,复合多个条件可让请求映射精确化。
类定义
@RequestMapping(value = "/user") public class UserController{
}
方法定义 映射请求地址:http://127.0.0.1:8080/应用名/user/register
@RequestMapping(value = "/register", method = RequestMethod.GET) public String register{ }
应用占位符
@RequestMapping(value = "/{formName}") public String loginForm(@PathVariable String formName) { // 动态跳转页面 return formName; }
3)如果类定义处没有设置@RequestMapping,则方法处标记的URL相对于WEB 应用的根目录
二、获取请求参数
1)RequestParam,将指定名称的参数赋值变量。如果是相同名称的变量,可省略注解@RequestParam
@RequestMapping(value = "/register", method = RequestMethod.POST) public String register(@RequestParam("loginname") String name1, @RequestParam("password") String password,@RequestParam("username") String name2) { return "loginForm"; }
2)RequestHeader,获取报文头参数
@RequestMapping(value="/test") public void requestHeaderTest(@RequestHeader("User-Agent") String userAgent, @RequestHeader(value="Accept") String[] accepts) { }
3)CookieValue
@RequestMapping(value="/cookie") public void cookiet(@CookieValue(value="JSESSIONID", defaultValue="") String sessionId) { }
4)能接受原生请求参数HttpServletRequest、HttpServletResponse、InputStream、OutputStream等
@RequestMapping("download.do") public ModelAndView download(String docNo,HttpServletRequest request, HttpServletResponse response) { }
5)上传附件
@RequestMapping("upload.do") public void upload(@RequestParam(value = "picFile", required = true)MultipartFilesoftwareFile,HttpServletRequest request) { String fileName = softwareFile.getOriginalFilename(); File targetSoftwareFile = new File("D:", fileName); if (!targetSoftwareFile.exists()) { targetSoftwareFile.mkdirs(); } try { softwareFile.transferTo(targetSoftwareFile); } catch (Exception e) { } }