传递单参数
@RequestMapping("/name")
public String getName(String name){
String retName = name;
return retName;
}
传递对象
@RequestMapping("/people")
public String getPeople(User user){
return user.toString();
}
传递多个参数
@RequestMapping("/names")
public String getNames(String name1,String name2){
String firstName = name1;
String secName = name2;
return name1 + " " + name2;
}
参数重命名
@RequestMapping("/rename")
public String rename(@RequestParam("haha")String name){
return name;
}
传递JSON对象
@RequestMapping("/getJSON")
public String getJson(@RequestBody User user){
return user.toString();
}
直接从 url 中传递参数 省略变量
@RequestMapping("/getMsg/{username}/{password}")
public String getMsg(@PathVariable("username") String username,@PathVariable("password") String password){
return username + " " + password;
}
@RequestMapping("/getOtherMsg/{username}/and/{password}")
public String getOtherMsg(@PathVariable("username") String username,@PathVariable("password") String password){
return username + " " + password;
}
上传文件
@RequestMapping("/upFile")
public String upFile(@RequestPart("myfile")MultipartFile file) throws IOException {
String path = "D:/home/ruoyi/result.png";
file.transferTo(new File(path));
return path;
}
获取Cookie
@RequestMapping("/getCookie")
public String getCookie(HttpServletRequest request){
Cookie[] cookies = request.getCookies();
return "getCookie";
}
@RequestMapping("/getOneCookie")
public String getOneCookie(@CookieValue("zhangsan") String val){
return "cookie +" + val;
}
获取Header
@RequestMapping("/getHeader")
public String getHeader(HttpServletRequest request){
String userAgent = request.getHeader("User-agent");
return userAgent;
}
@RequestMapping("/getSpringHeader")
public String getSpringHeader(@RequestHeader("User-Agent") String userAgent){
return userAgent;
}
设置Session
@RequestMapping("/setSession")
public String setSession(HttpServletRequest request){
HttpSession session = request.getSession(true);
if (session != null){
session.setAttribute("username","spring");
}
return (String) session.getAttribute("username");
}
读取Session
@RequestMapping("/getSession")
public String getSession(HttpServletRequest request){
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("username") != null){
return (String) session.getAttribute("username");
}else {
return "无session信息";
}
}
@RequestMapping("/getSpringSession")
public String getSpringSession(@SessionAttribute(value = "username",required = false) String username){
return username;
}