Spring MVC(学习笔记三)--控制器的注解(二) -之处理方法的参数配置

Handler Methods(处理方法)
1,参数的配置操作
类名:HandlerMethodArgumentsController(访问路径:/hmac)
@PathVariable
属性:name=value:参数名;required:是否必须有参数(默认=true)
/**
* 访问路径:http://localhost:8080/hmac/gpv/1
* @param id 传的参数,类型为int型
*/
@GetMapping(value = "gpv/{id}")
public String getPathVar(@PathVariable(name = "id") int id) {
    System.out.println(id);
    return "index";
}
@MatrixVariable
 1.在spring-mvc.xml中开启MatrixVariable的使用:
<mvc:annotation-driven enable-matrix-variables="true"/>
 2.请求路径注意事项:
 2.1 必须有路径变量@PathVariable
2.2 传值: ;key=value;key=value
/**
* 访问路径:http://localhost:8080/hmac/gmv/1;name=my
*/
@GetMapping(value = "gmv/{id}")
public String getMaxVar(@PathVariable(name = "id") int id, @MatrixVariable(name = "name") String name) {
    System.out.println(id+":"+name);
    return "index";
}
@RequestParam (获取参数)

属性:name=value:参数名;required:是否必须有参数(默认=true);defaultValue:默认参数
/**
* 请求路径:http://localhost:8080/hmac/grp?ids=10001
*/
@GetMapping(value = "grp")
public String getReqParam(@RequestParam(name = "ids") int id) {
    System.out.println(id);
    return "index";
}
@RequestHeader (取得标头信息)
属性:name=value:参数名;required:是否必须有参数(默认=true);defaultValue:默认参数
/**
* 可以取得标头Host的信息
* 访问路径:http://localhost:8080/hmac/grh
*/
@GetMapping(value = "grh")
public String getReqHeaders(@RequestHeader(name = "Host") String host) {
   System.out.println(host);
   return "index";
}
@CookieValue (取得标头中的Cookie的值)
 属性:name=value:参数名;required:是否必须有参数(默认=true);defaultValue:默认参数
/**
* 使用@ cookievalue标注绑定HTTP cookie控制器中的方法参数的值。
* 访问路径:http://localhost:8080/hmac/ghc
*/
@GetMapping("/ghc")
public void getHandleCookie(@CookieValue("JSESSIONID") String cookie) {
   System.out.println(cookie);
}
@RequestBody (取得提交实体的内容)
 属性:required:是否必须有参数(默认=true)
 RequestMappingController类:
/**
* @param body 提交的内容实体
*/
@PostMapping(value = "grb")
public String getRequestBody(@RequestBody String body) {
    System.out.println(body);
    return "index";
}
 index.jsp页面
<h1>requestBody:</h1>
<form action="${pageContext.request.contextPath}/hmac/grb" method="post">
     <input type="text" name="id" value="1001">
     <input type="text" name="name" value="mj">
     <input type="text" name="content" value="test">
     <input type="submit" value="sub">
</form> 
HttpEntity (取得标头信息和实体内容) 
 RequestMappingController类:
@PostMapping(value = "/ghe")
public String getHttpEntity(HttpEntity<String> entity) {
    entity.getHeaders().get("Host");//标头信息
    entity.getBody();//内容体信息
    return "index";
}
 index.jsp页面:
<h1>HttpEntity:</h1>
<form action="${pageContext.request.contextPath}/hmac/ghe" method="post">
     <input type="text" name="id" value="1001">
     <input type="text" name="name" value="mj">
     <input type="text" name="content" value="test">
     <input type="submit" value="sub">
</form>
Map(Map,Model,ModelMap都是用来封装模型数据,用来给视图做展示)
 RequestMappingController类:
@GetMapping(value = "gem")
public String getEntityMap(Map map) {
    // map.put  ()---->  (request)view ---->  ${}
    map.put("userName", "mj"); //request.setAttribute("name","mj")
    return "index";
}
 index.jsp页面:
hello: <b>${userName}</b>
Model (这里我用来取得外部跳转的参数)
 属性: addAttributeaddAttributies;containsAttribute;asMap
@GetMapping(value = "grv")
public String getRedirectVal(Model model) {
    Object obj = model.asMap().get("id");
    System.out.println(obj);
    return "index";
}
RedirectAttributes (外部跳转参数处理操作)

1、redirectAttributes.addAttribute("prama",value);相当于在重定向链接地址追加传递的参数
等同于:return:"redirect:/hamc/grh?id=10001 "
注意这种方法直接将传递的参数暴露在链接地址上,非常的不安全,慎用。
 @GetMapping(value = "gra")
 public String getRedirectAttr(RedirectAttributes redirectAttributes) {
    redirectAttributes.addAttribute("id","10001"); //url
    return "redirect:/hmac/grh";
 }
 2、 redirectAttributes.addFlashAttribute("prama",value);这种方法是隐藏了参数,链接地址上不直接暴露,
 但是能且只能在重定向的 页面” 获取prama参数值。
 其原理就是放到session中,session在跳到页面后马上移除对象(一次性使用)
@GetMapping(value = "gra")
public String getRedirectAttr(RedirectAttributes redirectAttributes) {
    //session 中存放
    redirectAttributes.addFlashAttribute("id", "100001");
    return "redirect:/hmac/grv";
}
@ModelAttribute (用于访问模型中的现有属性(如果不存在,实例化),应用数据绑定和验证(封装在数据模型中))
数据绑定可能会导致错误。默认情况下,在控制器的方法中检测BindException出现,添加一个BindingResult参数紧靠@ModelAttribute如下所示:
@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {
    if (result.hasErrors()) {
        return "petForm";
    }
    // ...
}
在某些情况下,您可能希望访问模型属性而不需要数据绑定。对于这样的情况你可以在控制器注入模型和直接或者设置@ModelAttribute(binding=false)如下图所示:
@ModelAttribute
public AccountForm setUpForm() {
    return new AccountForm();
}

@ModelAttribute
public Account findAccount(@PathVariable String accountId) {
    return accountRepository.findOne(accountId);
}

@PostMapping("update")
public String update(@Valid AccountUpdateForm form, BindingResult result,
            @ModelAttribute(binding=false) Account account) {
    // ...
}
@RequestPart (访问的一部分,在一个“multipart/form-data”请求)
@PostMapping("/")
public String handle(@RequestPart("meta-data") MetaData metadata,
        @RequestPart("file-data") MultipartFile file) {
    // ...
}


@SessionAttributes (类型级别的注释,用来存储模型中的属性之间的HTTP Servlet会话请求)
 这里@SessionAttributes写的“name”和下面的@SessionAttribute引号里的"name"要同名
@Controller
@RequestMapping(value = "/rhm")
@SessionAttributes(value = "name")
public class ReqHandlerMethodController {
    // ...
}
@SessionAttribute (访问任何会话属性,处理模型数据)
  属性:name=value:参数名, required:是否必须有参数(默认=true)
@GetMapping(value = "gsea")
public String getSessionAttr(@SessionAttribute(name = "name") String name) {
    System.out.println(name);
    return "index";
}
@RequestAttribute (用来访问先前请求属性之前创建的)
@PostMapping(value = "grea")
public String getReqAttr(@RequestAttribute(name = "org.springframework.web.servlet.HandlerMapping.bestMatchingPattern") String name) {
        return "index";
}

使用POJO对象传递参数(Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配,自动为该对象填充属性值。支持级联属性)

@PostMapping(value = "gfo")
public String  getFormObject(User user){
    return "index";
}
使用 Servlet API 作为入参(SpringMVC支持将Servlet API 作为入参传递给Controller的处理方法。 )

可接收的类型如下:

  • HttpServletRequest
  • HttpServletResponse
  • HttpSession
  • java.security.Principal
  • Locale
  • InputStream
  • OutputStream
  • Reader
  • Writer
    @GetMapping(value = "gsa")
    public String getServletApi(WebRequest request, HttpServletRequest request1, HttpSession session){
        return "index";
    }

猜你喜欢

转载自blog.csdn.net/qq_40594137/article/details/79226866
今日推荐