下面列出了怎么用org.springframework.web.bind.annotation.RequestBody的API类实例代码及写法,或者点击链接到github查看源代码。
@ApiOperation(value = "", nickname = "postViewConfig", notes = "Update view configuration", authorizations = {
@Authorization(value = "jenkins_auth")
}, tags={ "remoteAccess", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully updated view configuration"),
@ApiResponse(code = 400, message = "An error has occurred - error message is embedded inside the HTML response", response = String.class),
@ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password"),
@ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password"),
@ApiResponse(code = 404, message = "View cannot be found on Jenkins instance") })
@RequestMapping(value = "/view/{name}/config.xml",
produces = { "*/*" },
consumes = { "application/json" },
method = RequestMethod.POST)
default ResponseEntity<Void> postViewConfig(@ApiParam(value = "Name of the view",required=true) @PathVariable("name") String name,@ApiParam(value = "View configuration in config.xml format" ,required=true ) @Valid @RequestBody String body,@ApiParam(value = "CSRF protection token" ) @RequestHeader(value="Jenkins-Crumb", required=false) String jenkinsCrumb) {
return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}
/**
* getJobUserList(获取调度系统用户 不带分页数据-服务)
*
* @param jobUser
* @return
* @author rufei.cn
*/
public List<JobUser> getJobUserList(@RequestBody JobUser jobUser) {
String parms = JSON.toJSONString(jobUser);
List<JobUser> list = null;
logger.info("getJobUserList(获取调度系统用户 不带分页数据-服务) 开始 parms={}", parms);
if (jobUser == null) {
return list;
}
try {
list = jobUserDao.getJobUserList(jobUser);
} catch (Exception e) {
String msg = "getJobUserList 异常 " + StringUtil.getExceptionMsg(e);
logger.error(msg);
sysCommonService.sendDingTalkMessage("base-service[getJobUserList]", parms, null, msg, this.getClass());
}
logger.info("getJobUserList(获取调度系统用户 不带分页数据-服务) 结束");
return list;
}
@ApiOperation(value = "Move a single timer job", tags = { "Jobs" })
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Indicates the timer job was moved. Response-body is intentionally empty."),
@ApiResponse(code = 404, message = "Indicates the requested job was not found."),
@ApiResponse(code = 500, message = "Indicates the an exception occurred while executing the job. The status-description contains additional detail about the error. The full error-stacktrace can be fetched later on if needed.")
})
@PostMapping("/management/timer-jobs/{jobId}")
public void executeTimerJobAction(@ApiParam(name = "jobId") @PathVariable String jobId, @RequestBody RestActionRequest actionRequest, HttpServletResponse response) {
if (actionRequest == null || !MOVE_ACTION.equals(actionRequest.getAction())) {
throw new FlowableIllegalArgumentException("Invalid action, only 'move' is supported.");
}
Job job = getTimerJobById(jobId);
try {
managementService.moveTimerToExecutableJob(job.getId());
} catch (FlowableObjectNotFoundException aonfe) {
// Re-throw to have consistent error-messaging across REST-api
throw new FlowableObjectNotFoundException("Could not find a timer job with id '" + jobId + "'.", Job.class);
}
response.setStatus(HttpStatus.NO_CONTENT.value());
}
@RequestMapping(value = "/query/prestate", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
@Timed(name = "query")
public SQLResponse prepareQuery(@RequestBody PrepareSqlRequest sqlRequest) {
long startTimestamp = System.currentTimeMillis();
SQLResponse response = doQuery(sqlRequest);
response.setDuration(System.currentTimeMillis() - startTimestamp);
queryService.logQuery(sqlRequest, response, new Date(startTimestamp), new Date(System.currentTimeMillis()));
if (response.getIsException()) {
String errorMsg = response.getExceptionMessage();
throw new InternalErrorException(QueryUtil.makeErrorMsgUserFriendly(errorMsg));
}
return response;
}
@RequestMapping(value = "/message", consumes = { "application/json" }, produces = {
MediaType.APPLICATION_JSON_VALUE }, method = RequestMethod.POST)
public ResponseEntity<Message> postMessage(@RequestBody Message msg) throws Exception {
msg.init();
System.out.println("Received message: " + msg);
if ("async1".equals(sendMode)) {
kafka.sendMessageAsync(msg, executor1);
System.out.println("Message sent async (executor1) to Kafka");
} else if ("async2".equals(sendMode)) {
kafka.sendMessageAsync(msg, executor2);
System.out.println("Message sent async (executor2) to Kafka");
} else {
kafka.sendMessage(msg);
System.out.println("Message sent sync to Kafka");
}
return new ResponseEntity<Message>(msg, HttpStatus.OK);
}
@RequestMapping(path=URL_PREFIX+"/group/{groupId}/queryData",
method=RequestMethod.POST,
consumes = MediaType.TEXT_PLAIN_VALUE,
produces = MediaType.TEXT_PLAIN_VALUE)
public String tradletGroupQueryData(@PathVariable(value="groupId") String groupId, @RequestBody String queryExpr){
TradletGroup g = null;
for(TradletGroup group:tradletService.getGroups()) {
if ( StringUtil.equalsIgnoreCase(groupId, group.getId()) ) {
g = group;
break;
}
}
if ( g==null ) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
return g.queryData(queryExpr);
}
@RequestMapping(value = "/stats",
method= RequestMethod.POST,
consumes="application/json",
produces="application/json")
public StatsResponse check(@RequestBody StatsRequest request) {
int bottles = this.statsService.findBottlesByName(request.getName());
String text = String.format("Dear %s thanks for your interested in drinking beer", request.getName());
return new StatsResponse(bottles, text);
}
/**
* POST /user/createWithList : Creates list of users with given input array
*
* @param body List of user object (required)
* @return successful operation (status code 200)
*/
@ApiOperation(value = "Creates list of users with given input array", nickname = "createUsersWithListInput", notes = "", tags={ "user", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation") })
@RequestMapping(value = "/user/createWithList",
method = RequestMethod.POST)
default CompletableFuture<ResponseEntity<Void>> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List<User> body) {
return CompletableFuture.completedFuture(new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED));
}
@RequestMapping(value = "", method = RequestMethod.POST) // SOLUTION
public void createCourse(@RequestBody CourseDto dto) throws ParseException { // SOLUTION
if (courseRepo.getByName(dto.name) != null) {
throw new IllegalArgumentException("Another course with that name already exists");
}
courseRepo.save(mapToEntity(dto));
}
/**
* 保存
*/
@SysLog("保存菜单")
@PostMapping
@PreAuthorize("@pms.hasPermission('sys:menu:save')")
public ResponseEntity<Void> save(@Valid @RequestBody SysMenu menu){
//数据校验
verifyForm(menu);
sysMenuService.save(menu);
return ResponseEntity.ok().build();
}
@PreAuthorize("@permissionService.hasPermission('blog:comment:add')")
@Log(title = "评论管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody @Validated Comment comment) {
comment.setCreateBy(SecurityUtils.getUsername());
return toAjax(commentService.insertComment(comment));
}
@ApiOperation(value = "", notes = "Update view configuration", response = Void.class, authorizations = {
@Authorization(value = "jenkins_auth")
}, tags={ "remoteAccess", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully updated view configuration"),
@ApiResponse(code = 400, message = "An error has occurred - error message is embedded inside the HTML response", response = String.class),
@ApiResponse(code = 401, message = "Authentication failed - incorrect username and/or password"),
@ApiResponse(code = 403, message = "Jenkins requires authentication - please set username and password"),
@ApiResponse(code = 404, message = "View cannot be found on Jenkins instance") })
@RequestMapping(value = "/view/{name}/config.xml",
produces = { "*/*" },
consumes = { "application/json" },
method = RequestMethod.POST)
ResponseEntity<Void> postViewConfig(@ApiParam(value = "Name of the view",required=true ) @PathVariable("name") String name,@ApiParam(value = "View configuration in config.xml format" ,required=true ) @RequestBody String body,@ApiParam(value = "CSRF protection token" ) @RequestHeader(value="Jenkins-Crumb", required=false) String jenkinsCrumb, @RequestHeader(value = "Accept", required = false) String accept) throws Exception;
@PostMapping
public ResponseEntity<Ingredient> postIngredient(@RequestBody Ingredient ingredient) {
Ingredient saved = repo.save(ingredient);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create("http://localhost:8080/ingredients/" + ingredient.getId()));
return new ResponseEntity<>(saved, headers, HttpStatus.CREATED);
}
@RequestMapping(value = "/system/settings/elastic", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public EsStatusAndSettings saveElasticSettings(@RequestBody @Valid final EsSettings settings) throws IOException {
settingsHolder.storeSettings(settings);
return getStatus(settings);
}
/**
* 更新定时任务
*
* @param quartzJob
* @return
*/
//@RequiresRoles({"admin"})
@RequestMapping(value = "/edit", method = RequestMethod.PUT)
public Result<?> eidt(@RequestBody QuartzJob quartzJob) {
try {
quartzJobService.editAndScheduleJob(quartzJob);
} catch (SchedulerException e) {
log.error(e.getMessage(),e);
return Result.error("更新定时任务失败!");
}
return Result.ok("更新定时任务成功!");
}
@RequestMapping(method = RequestMethod.POST)
public Bookmark createBookmark(@PathVariable String userId,
@RequestBody Bookmark bookmark) {
Bookmark bookmarkInstance = new Bookmark(userId, bookmark.getHref(),
bookmark.getDescription(), bookmark.getLabel());
return this.bookmarkRepository.save(bookmarkInstance);
}
@PostMapping("paras/get")
@ApiOperation(value = "get by method and paras", httpMethod = "POST")
public CommonResponse getByMethodParas(@RequestBody @Valid UnitParaQueryPageReq<String> req, BindingResult result) {
if (result.hasErrors()) {
return ResponseUtils.validateError(result);
}
return methodManager.getPageListByReq(req);
}
/**
* 查询MQ topic列表.
*
* @param tpcMqTopic the tpc mq topic
*
* @return the wrapper
*/
@PostMapping(value = "/queryTopicListWithPage")
@ApiOperation(httpMethod = "POST", value = "查询MQ topic列表")
public Wrapper<List<TpcMqTopicVo>> queryTopicListWithPage(@ApiParam(name = "topic", value = "MQ-Topic") @RequestBody TpcMqTopic tpcMqTopic) {
logger.info("查询角色列表tpcMqTopicQuery={}", tpcMqTopic);
List<TpcMqTopicVo> list = tpcMqTopicService.listWithPage(tpcMqTopic);
return WrapMapper.ok(list);
}
@RequestMapping(value = "", method = RequestMethod.POST)
public FormValidationResultRepresentation<CommentVoteForm> createCommentVote(@RequestBody @Valid CommentVoteForm commentVoteForm, BindingResult bindingResult) {
log.debug("createCommentVote() - commentVoteForm: {}", commentVoteForm);
if (bindingResult.hasErrors()) {
final List<FormErrorRepresentation> formErrors = ValidationUtil.extractFormErrors(bindingResult);
return new FormValidationResultRepresentation<>(commentVoteForm, formErrors);
}
final CommentVoteForm createdForm = commentVoteManagementService.createCommentVote(commentVoteForm);
return new FormValidationResultRepresentation<>(createdForm);
}
@RequestMapping(value = "/save")
@RequiresPermissions(value = {"iam:menu"})
public RespBase<?> save(@RequestBody Menu menu) {
RespBase<Object> resp = RespBase.create();
menuService.save(menu);
return resp;
}
@PreAuthorize("@roleChecker.hasValidRole(#principal)")
@RequestMapping(value="/company", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CompanyDTO> createCompany(
Principal principal,
@RequestBody CompanyDTO companyDTO) {
// Check for SUPERADMIN role
// RoleChecker.hasValidRole(principal);
companyDTO = companyService.create(companyDTO);
return new ResponseEntity<CompanyDTO>(companyDTO, HttpStatus.CREATED);
}
/**
* Edits a Group, belonging to the current session account.
*
* @param groupId The group ID.
* @param editGroupDto Object with the necessary data to edit the Group.
* @return Object with the edited group data.
*/
@PostMapping("/{group-id}")
public GroupDto editGroup(
@PathVariable(name = "group-id", required = true) @NotNull UUID groupId,
@RequestBody(required = true) @Valid EditGroupDto editGroupDto) {
editGroupDto.setGroupId(groupId);
return groupsService.editGroup(sessionAccount.getAccountId(), editGroupDto);
}
@PostMapping(value = "/update")
public ResponseEntity<Map<String, Object>> updateAttribute(@RequestBody Attribute attribute) {
Map<String, Object> response = new HashMap<>();
try {
AttributeModel model = attributeConverter.convert(attribute);
model = attributeService.saveAttribute(model);
Attribute result = attributeModelConverter.convert(model);
response.put("Result", "OK");
response.put("Records", result);
} catch (Exception ex) {
response.put("Result", "FAILURE");
}
return new ResponseEntity<>(response, HttpStatus.OK);
}
@AuthorityVerify
@OperationLogger(value = "置顶资源分类")
@ApiOperation(value = "置顶分类", notes = "置顶分类", response = String.class)
@PostMapping("/stick")
public String stick(@Validated({Delete.class}) @RequestBody ResourceSortVO resourceSortVO, BindingResult result) {
// 参数校验
ThrowableUtils.checkParamArgument(result);
return resourceSortService.stickResourceSort(resourceSortVO);
}
@RequestMapping(method = RequestMethod.PUT, path = "/greeting/{id}")
public Greeting add(@PathVariable Integer id,
@RequestBody Greeting greeting)
throws NoSuchRequestHandlingMethodException {
try {
return data.updateGreeting(id, greeting);
} catch (IndexOutOfBoundsException e) {
throw new NoSuchRequestHandlingMethodException("greeting",
GreetingController.class);
}
}
/**
* 更新公司信息
*
* @param companyId
* @return
*/
@RequestMapping(value = "/{companyId}", method = { RequestMethod.PUT })
@Interceptors({ CompanyAdminRequired.class, CompanyChecking.class })
@ResponseBody
public CompanyDTO updateCompany(@PathVariable int companyId, @RequestBody CompanyDTO form) {
form.setId(companyId);
companyService.updateSelective(CompanyTransform.companyDTOtoCompany(form));
return form;
}
@AuthorityVerify
@OperationLogger(value = "批量删除博客分类")
@ApiOperation(value = "批量删除博客分类", notes = "批量删除博客分类", response = String.class)
@PostMapping("/deleteBatch")
public String delete(@Validated({Delete.class}) @RequestBody List<BlogSortVO> blogSortVoList, BindingResult result) {
// 参数校验
ThrowableUtils.checkParamArgument(result);
return blogSortService.deleteBatchBlogSort(blogSortVoList);
}
@PostMapping("/addFoos")
@ResponseStatus(HttpStatus.ACCEPTED)
public Flux<Foo> addFoos(@RequestBody List<Foo> list) {
Flux<Foo> flux = Flux.fromIterable(list).cache();
flux.subscribe(value -> this.list.add(value.getValue()));
return flux;
}
@RequestMapping(path = RestPaths.MANAGEMENT_GET_GROUP_OPERATIONS_RELATIVE_PATH, method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public GetGroupOperationsResponse getGroupOperations(@RequestBody GetGroupOperationsRequest request) {
GetGroupOperationsResponse response = groupService.getGroupOperations(request);
MetricLoggerHelper.logResponseEvent("management-group", "get-group-operations", response);
return response;
}
@PostMapping(path = "/buddyList/updateUserSignInfo")
BaseModel<?> updateUserSignInfo(@RequestBody BuddyListUserSignInfoReq signInfoReq);
如果文章对你有帮助,欢迎点击上方按钮打赏作者