Java Code Examples for org.springframework.web.bind.annotation.RequestAttribute

The following examples show how to use org.springframework.web.bind.annotation.RequestAttribute. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
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);
 
Example 2
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);
 
Example 3
@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;
        }
    };
}
 
Example 4
@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));
}
 
Example 5
@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));
}
 
Example 6
@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));
}
 
Example 7
Source Project: authmore-framework   Source File: TokenEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 8
@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()));
}
 
Example 9
@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) {
}
 
Example 10
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";
}
 
Example 11
@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) {
}
 
Example 12
Source Project: spring-analysis-note   Source File: MvcAnnotationPredicates.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 13
@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()));
}
 
Example 14
@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) {
}
 
Example 15
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";
}
 
Example 16
@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) {
}
 
Example 17
Source Project: java-technology-stack   Source File: MvcAnnotationPredicates.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 18
Source Project: BlogManagePlatform   Source File: DefaultRequiredPlugin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取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;
}
 
Example 19
@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);
}
 
Example 20
@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));
}
 
Example 21
@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));
}
 
Example 22
@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));
}
 
Example 23
@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));
}
 
Example 24
@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));
}
 
Example 25
@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;
}
 
Example 26
@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);
}
 
Example 27
@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);
}
 
Example 28
@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);
}
 
Example 29
@Override
public String getParameterName(RequestAttribute annotation) {
  String value = annotation.value();
  if (value.isEmpty()) {
    value = annotation.name();
  }
  return value;
}
 
Example 30
@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);
}