org.springframework.web.bind.annotation.RequestAttribute源码实例Demo

类org.springframework.web.bind.annotation.RequestAttribute源码实例Demo

下面列出了怎么用org.springframework.web.bind.annotation.RequestAttribute的API类实例代码及写法,或者点击链接到github查看源代码。

String handleInInterface(
@CookieValue("cookie") int cookieV,
@PathVariable("pathvar") String pathvarV,
@RequestHeader("header") String headerV,
@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
@RequestHeader Map<String, Object> headerMap,
@RequestParam("dateParam") Date dateParam,
@RequestParam Map<String, Object> paramMap,
String paramByConvention,
@Value("#{request.contextPath}") String value,
@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
Errors errors,
TestBean modelAttrByConvention,
Color customArg,
HttpServletRequest request,
HttpServletResponse response,
@SessionAttribute TestBean sessionAttribute,
@RequestAttribute TestBean requestAttribute,
User user,
@ModelAttribute OtherUser otherUser,
Model model,
UriComponentsBuilder builder);
 
String handleInInterface(
@CookieValue("cookie") int cookieV,
@PathVariable("pathvar") String pathvarV,
@RequestHeader("header") String headerV,
@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
@RequestHeader Map<String, Object> headerMap,
@RequestParam("dateParam") Date dateParam,
@RequestParam Map<String, Object> paramMap,
String paramByConvention,
@Value("#{request.contextPath}") String value,
@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
Errors errors,
TestBean modelAttrByConvention,
Color customArg,
HttpServletRequest request,
HttpServletResponse response,
@SessionAttribute TestBean sessionAttribute,
@RequestAttribute TestBean requestAttribute,
User user,
@ModelAttribute OtherUser otherUser,
Model model,
UriComponentsBuilder builder);
 
@Override
public BindingResult<Object> bind(ArgumentConversionContext<Object> context, HttpRequest<?> source) {
    final AnnotationMetadata annotationMetadata = context.getAnnotationMetadata();
    final boolean required = annotationMetadata.getValue("required", boolean.class).orElse(true);
    final String name = annotationMetadata.getValue(RequestAttribute.class, String.class).orElseGet(() ->
            annotationMetadata.getValue(RequestAttribute.class, "name", String.class).orElse(context.getArgument().getName())
    );

    return new BindingResult<Object>() {
        @Override
        public Optional<Object> getValue() {
            return source.getAttributes().get(name, context);
        }

        @Override
        public boolean isSatisfied() {
            return !required;
        }
    };
}
 
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "authenticated user"),
    @ApiResponse(code = 403, response = String.class, message = "unauthenticated user")
})
@RequestMapping(value = "bookings", method = POST, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> book(@RequestAttribute String customerId) {
  if (!customers.contains(customerId)) {
    throw new InvocationException(FORBIDDEN, "No such customer with id " + customerId);
  }

  return ResponseEntity.ok(String.format("{\n"
          + "  \"body\": \"Flight booked with id %s for customer %s\"\n"
          + "}",
      UUID.randomUUID().toString(),
      customerId));
}
 
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "authenticated user"),
    @ApiResponse(code = 403, response = String.class, message = "unauthenticated user"),
    @ApiResponse(code = 400, response = String.class, message = "insufficient account balance")
})
@RequestMapping(value = "payments", method = POST, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> pay(@RequestAttribute String customerId) {
  if ("anonymous".equals(customerId)) {
    throw new InvocationException(FORBIDDEN, "No such customer with id " + customerId);
  }

  if (balance < 800) {
    throw new InvocationException(BAD_REQUEST, "Not enough balance in account of customer " + customerId);
  }

  balance -= 800;
  return ResponseEntity.ok(String.format("{\n"
          + "  \"body\": \"Payment made for customer %s and remaining balance is %d\"\n"
          + "}",
      customerId,
      balance));
}
 
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "authenticated user"),
    @ApiResponse(code = 403, response = String.class, message = "unauthenticated user")
})
@RequestMapping(value = "reservations", method = POST, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> reserve(@RequestAttribute String customerId) {
  if (!customers.contains(customerId)) {
    throw new InvocationException(FORBIDDEN, "No such customer with id " + customerId);
  }

  return ResponseEntity.ok(String.format("{\n"
          + "  \"body\": \"Hotel reserved with id %s for customer %s\"\n"
          + "}",
      UUID.randomUUID().toString(),
      customerId));
}
 
源代码7 项目: authmore-framework   文件: TokenEndpoint.java
@PostMapping("/oauth/token")
public TokenResponse token(
        @RequestParam(value = "grant_type", required = false) String grantType,
        @RequestParam(value = "code", required = false) String code,
        @RequestParam(value = "redirect_uri", required = false) String redirectUri,
        @RequestParam(value = "client_id", required = false) String clientId,
        @RequestParam(value = "username", required = false) String username,
        @RequestParam(value = "password", required = false) String password,
        @RequestParam(value = "scope", required = false) String scope,
        @RequestParam(value = "refresh_token", required = false) String refreshToken,
        @RequestAttribute(RequestProperties.CURRENT_CLIENT) ClientDetails client) {
    GrantTypes realType = GrantTypes.eval(grantType);
    if (isEmpty(clientId))
        throw new OAuthException(OAuthException.INVALID_CLIENT);
    switch (realType) {
        case AUTHORIZATION_CODE:
            return authorizationCodeTokenIssuer.issue(client, redirectUri, code);
        case PASSWORD:
            return passwordTokenIssuer.issue(client, username, password, scope);
        case CLIENT_CREDENTIALS:
            return clientCredentialsTokenIssuer.issue(client, scope);
        case REFRESH_TOKEN:
            return refreshTokenIssuer.issue(client, refreshToken);
        default:
            throw new OAuthException(OAuthException.UNSUPPORTED_GRANT_TYPE);
    }
}
 
@Test
public void supportsParameter() {
	assertTrue(this.resolver.supportsParameter(
			this.testMethod.annot(requestAttribute().noName()).arg(Foo.class)));

	// SPR-16158
	assertTrue(this.resolver.supportsParameter(
			this.testMethod.annotPresent(RequestAttribute.class).arg(Mono.class, Foo.class)));

	assertFalse(this.resolver.supportsParameter(
			this.testMethod.annotNotPresent(RequestAttribute.class).arg()));
}
 
@SuppressWarnings({"unused", "OptionalUsedAsFieldOrParameterType"})
private void handleWithRequestAttribute(
		@RequestAttribute Foo foo,
		@RequestAttribute("specialFoo") Foo namedFoo,
		@RequestAttribute(name="foo", required = false) Foo notRequiredFoo,
		@RequestAttribute(name="foo") Optional<Foo> optionalFoo,
		@RequestAttribute Mono<Foo> fooMono,
		String notSupported) {
}
 
public String handle(
		@CookieValue("cookie") int cookieV,
		@PathVariable("pathvar") String pathvarV,
		@RequestHeader("header") String headerV,
		@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
		@RequestHeader Map<String, Object> headerMap,
		@RequestParam("dateParam") Date dateParam,
		@RequestParam Map<String, Object> paramMap,
		String paramByConvention,
		@Value("#{request.contextPath}") String value,
		@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
		Errors errors,
		TestBean modelAttrByConvention,
		Color customArg,
		HttpServletRequest request,
		HttpServletResponse response,
		@SessionAttribute TestBean sessionAttribute,
		@RequestAttribute TestBean requestAttribute,
		User user,
		@ModelAttribute OtherUser otherUser,
		Model model,
		UriComponentsBuilder builder) {

	model.addAttribute("cookie", cookieV).addAttribute("pathvar", pathvarV).addAttribute("header", headerV)
			.addAttribute("systemHeader", systemHeader).addAttribute("headerMap", headerMap)
			.addAttribute("dateParam", dateParam).addAttribute("paramMap", paramMap)
			.addAttribute("paramByConvention", paramByConvention).addAttribute("value", value)
			.addAttribute("customArg", customArg).addAttribute(user)
			.addAttribute("sessionAttribute", sessionAttribute)
			.addAttribute("requestAttribute", requestAttribute)
			.addAttribute("url", builder.path("/path").build().toUri());

	assertNotNull(request);
	assertNotNull(response);

	return "viewName";
}
 
@SuppressWarnings("unused")
private void handleWithRequestAttribute(
		@RequestAttribute Foo foo,
		@RequestAttribute("specialFoo") Foo namedFoo,
		@RequestAttribute(name="foo", required = false) Foo notRequiredFoo,
		@RequestAttribute(name="foo") Optional<Foo> optionalFoo) {
}
 
@Override
public boolean test(MethodParameter parameter) {
	RequestAttribute annotation = parameter.getParameterAnnotation(RequestAttribute.class);
	return annotation != null &&
			(this.name == null || annotation.name().equals(this.name)) &&
			annotation.required() == this.required;
}
 
@Test
public void supportsParameter() throws Exception {

	assertTrue(this.resolver.supportsParameter(
			this.testMethod.annot(requestAttribute().noName()).arg(Foo.class)));

	// SPR-16158
	assertTrue(this.resolver.supportsParameter(
			this.testMethod.annotPresent(RequestAttribute.class).arg(Mono.class, Foo.class)));

	assertFalse(this.resolver.supportsParameter(
			this.testMethod.annotNotPresent(RequestAttribute.class).arg()));
}
 
@SuppressWarnings({"unused", "OptionalUsedAsFieldOrParameterType"})
private void handleWithRequestAttribute(
		@RequestAttribute Foo foo,
		@RequestAttribute("specialFoo") Foo namedFoo,
		@RequestAttribute(name="foo", required = false) Foo notRequiredFoo,
		@RequestAttribute(name="foo") Optional<Foo> optionalFoo,
		@RequestAttribute Mono<Foo> fooMono,
		String notSupported) {
}
 
public String handle(
		@CookieValue("cookie") int cookieV,
		@PathVariable("pathvar") String pathvarV,
		@RequestHeader("header") String headerV,
		@RequestHeader(defaultValue = "#{systemProperties.systemHeader}") String systemHeader,
		@RequestHeader Map<String, Object> headerMap,
		@RequestParam("dateParam") Date dateParam,
		@RequestParam Map<String, Object> paramMap,
		String paramByConvention,
		@Value("#{request.contextPath}") String value,
		@ModelAttribute("modelAttr") @Valid TestBean modelAttr,
		Errors errors,
		TestBean modelAttrByConvention,
		Color customArg,
		HttpServletRequest request,
		HttpServletResponse response,
		@SessionAttribute TestBean sessionAttribute,
		@RequestAttribute TestBean requestAttribute,
		User user,
		@ModelAttribute OtherUser otherUser,
		Model model,
		UriComponentsBuilder builder) {

	model.addAttribute("cookie", cookieV).addAttribute("pathvar", pathvarV).addAttribute("header", headerV)
			.addAttribute("systemHeader", systemHeader).addAttribute("headerMap", headerMap)
			.addAttribute("dateParam", dateParam).addAttribute("paramMap", paramMap)
			.addAttribute("paramByConvention", paramByConvention).addAttribute("value", value)
			.addAttribute("customArg", customArg).addAttribute(user)
			.addAttribute("sessionAttribute", sessionAttribute)
			.addAttribute("requestAttribute", requestAttribute)
			.addAttribute("url", builder.path("/path").build().toUri());

	assertNotNull(request);
	assertNotNull(response);

	return "viewName";
}
 
@SuppressWarnings("unused")
private void handleWithRequestAttribute(
		@RequestAttribute Foo foo,
		@RequestAttribute("specialFoo") Foo namedFoo,
		@RequestAttribute(name="foo", required = false) Foo notRequiredFoo,
		@RequestAttribute(name="foo") Optional<Foo> optionalFoo) {
}
 
@Override
public boolean test(MethodParameter parameter) {
	RequestAttribute annotation = parameter.getParameterAnnotation(RequestAttribute.class);
	return annotation != null &&
			(this.name == null || annotation.name().equals(this.name)) &&
			annotation.required() == this.required;
}
 
源代码18 项目: BlogManagePlatform   文件: DefaultRequiredPlugin.java
/**
 * 获取spring系列注解中的必填设置
 * @author Frodez
 * @date 2019-06-11
 */
private boolean requestXXX(ResolvedMethodParameter methodParameter) {
	Optional<RequestAttribute> requestAttribute = methodParameter.findAnnotation(RequestAttribute.class);
	if (requestAttribute.isPresent()) {
		return requestAttribute.get().required();
	}
	Optional<RequestBody> requestBody = methodParameter.findAnnotation(RequestBody.class);
	if (requestBody.isPresent()) {
		return requestBody.get().required();
	}
	Optional<RequestHeader> requestHeader = methodParameter.findAnnotation(RequestHeader.class);
	if (requestHeader.isPresent()) {
		return requestHeader.get().required();
	}
	Optional<RequestParam> requestParam = methodParameter.findAnnotation(RequestParam.class);
	if (requestParam.isPresent()) {
		return requestParam.get().required();
	}
	Optional<RequestPart> requestPart = methodParameter.findAnnotation(RequestPart.class);
	if (requestPart.isPresent()) {
		return requestPart.get().required();
	}
	Optional<PathVariable> pathVariable = methodParameter.findAnnotation(PathVariable.class);
	if (pathVariable.isPresent()) {
		return pathVariable.get().required();
	}
	return false;
}
 
@RequestMapping(value = "/usableResource", method = POST, consumes = APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> postUsableResource(
    @RequestAttribute(name = "hello") String who,
    @RequestAttribute(name = "response") String response) {

  return ResponseEntity.ok("hello " + who + ", with response " + response);
}
 
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "authenticated user"),
    @ApiResponse(code = 403, response = String.class, message = "unauthenticated user")
})
@RequestMapping(value = "bookings", method = PUT, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> cancel(@RequestAttribute String customerId) {
  if (!customers.contains(customerId)) {
    throw new InvocationException(FORBIDDEN, "No such customer with id " + customerId);
  }

  return ResponseEntity.ok(String.format("Flight booking cancelled with id %s for customer %s",
      UUID.randomUUID().toString(),
      customerId));
}
 
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "authenticated user"),
    @ApiResponse(code = 403, response = String.class, message = "unauthenticated user")
})
@RequestMapping(value = "payments", method = PUT, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> refund(@RequestAttribute String customerId) {
  if ("anonymous".equals(customerId)) {
    throw new InvocationException(FORBIDDEN, "No such customer with id " + customerId);
  }

  balance += 800;
  return ResponseEntity.ok(String.format("Payment refunded for customer %s and remaining balance is %d",
      customerId,
      balance));
}
 
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "authenticated user"),
    @ApiResponse(code = 403, response = String.class, message = "unauthenticated user")
})
@RequestMapping(value = "reservations", method = PUT, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> cancel(@RequestAttribute String customerId) {
  if (!customers.contains(customerId)) {
    throw new InvocationException(FORBIDDEN, "No such customer with id " + customerId);
  }

  return ResponseEntity.ok(String.format("Hotel reservation cancelled with id %s for customer %s",
      UUID.randomUUID().toString(),
      customerId));
}
 
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "authenticated user"),
    @ApiResponse(code = 403, response = String.class, message = "unauthenticated user")
})
@RequestMapping(value = "rentals", method = POST, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> rent(@RequestAttribute String customerId) {
  log.info("Received car rental request from customer {}", customerId);
  if (!customers.contains(customerId)) {
    log.info("No such customer {}", customerId);
    throw new InvocationException(FORBIDDEN, "No such customer with id " + customerId);
  }

  if ("snail".equals(customerId)) {
    try {
      log.info("Encountered extremely slow customer {}", customerId);
      int timeout = delay;
      delay = 0;
      TimeUnit.SECONDS.sleep(timeout);
      log.info("Finally served the extremely slow customer {}", customerId);
    } catch (InterruptedException e) {
      return new ResponseEntity<>("Interrupted", INTERNAL_SERVER_ERROR);
    }
  }

  return ResponseEntity.ok(String.format("{\n"
          + "  \"body\": \"Car rented with id %s for customer %s\"\n"
          + "}",
      UUID.randomUUID().toString(),
      customerId));
}
 
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "authenticated user"),
    @ApiResponse(code = 403, response = String.class, message = "unauthenticated user")
})
@RequestMapping(value = "rentals", method = PUT, consumes = APPLICATION_FORM_URLENCODED_VALUE, produces = TEXT_PLAIN_VALUE)
public ResponseEntity<String> cancel(@RequestAttribute String customerId) {
  if (!customers.contains(customerId)) {
    throw new InvocationException(FORBIDDEN, "No such customer with id " + customerId);
  }

  return ResponseEntity.ok(String.format("Car rental cancelled with id %s for customer %s",
      UUID.randomUUID().toString(),
      customerId));
}
 
@RequestMapping(path = "/uploadArrayWithoutAnnotation", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadArrayWithoutAnnotation(MultipartFile[] file1, MultipartFile[] file2,
    @RequestAttribute("name") String name) {
  List<MultipartFile> multipartFileList = new ArrayList<>();
  multipartFileList.addAll(Arrays.asList(file1));
  multipartFileList.addAll(Arrays.asList(file2));
  return _fileUpload(multipartFileList) + name;
}
 
@ResponseHeaders({@ResponseHeader(name = "h1", response = String.class),
    @ResponseHeader(name = "h2", response = String.class)})
@PostMapping(path = "/responseEntity")
@Override
public ResponseEntity<Date> responseEntity(InvocationContext c1, @RequestAttribute("date") Date date) {
  return super.responseEntity(c1, date);
}
 
@ResponseHeaders({@ResponseHeader(name = "h1", response = String.class),
    @ResponseHeader(name = "h2", response = String.class)})
@RequestMapping(path = "/responseEntity", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@Override
public ResponseEntity<Date> responseEntity(InvocationContext c1, @RequestAttribute("date") Date date) {
  return super.responseEntity(c1, date);
}
 
@ResponseHeaders({@ResponseHeader(name = "h1", response = String.class),
    @ResponseHeader(name = "h2", response = String.class)})
@RequestMapping(path = "/responseEntity", method = RequestMethod.POST)
public ResponseEntity<Date> responseEntity(InvocationContext c1, @RequestAttribute("date") Date date) {
  HttpHeaders headers = new HttpHeaders();
  headers.add("h1", "h1v " + c1.getContext().get(Const.SRC_MICROSERVICE));

  InvocationContext c2 = ContextUtils.getInvocationContext();
  headers.add("h2", "h2v " + c2.getContext().get(Const.SRC_MICROSERVICE));

  return new ResponseEntity<>(date, headers, HttpStatus.ACCEPTED);
}
 
@Override
public String getParameterName(RequestAttribute annotation) {
  String value = annotation.value();
  if (value.isEmpty()) {
    value = annotation.name();
  }
  return value;
}
 
@RequestMapping(
    path = "usingRequestMapping/{targetName}",
    method = {RequestMethod.POST},
    consumes = {"text/plain", "application/*"},
    produces = {"text/plain", "application/*"})
public String usingRequestMapping(@RequestBody User srcUser, @RequestHeader String header,
    @PathVariable String targetName, @RequestParam(name = "word") String word, @RequestAttribute String form) {
  return String.format("%s %s %s %s %s", srcUser.name, header, targetName, word, form);
}
 
服务器费用不足...
 类方法
支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者