gpt4 book ai didi

java - 使用 @RequestParam 发布 JSON

转载 作者:行者123 更新时间:2023-12-01 12:11:26 26 4
gpt4 key购买 nike

在我的应用程序中,我有这个方法:

RequestMapping(value = "/variable/add", method = RequestMethod.POST)
public @ResponseBody
Object addVariable(@RequestBody MyObject myObject) {
//do something
return saimVariable;
}

和身份验证方面:

@Around("execution(* pl.my.company.*.*(..))")
public Object advice(ProceedingJoinPoint joinPoint) {
ServletRequestAttributes t = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
HttpServletRequest request = t.getRequest();

String username = (String) request.getParameter("username");
System.out.println("USER : " + username);
try {
if (username.equals("myname")) {
System.out.println("*** ACCESS GRANTED *** ");
Object response = joinPoint.proceed();
return response;
} else {
System.out.println();
return "ACCESS DENIED";
}

} catch (Throwable e) {
System.out.println(e.getMessage());
return "ACCESS DENIED";
}

}

}

我想创建 REST 服务,因此对于 securitu,我需要验证每个请求,因此我还需要传递一个用户名,而不仅仅是一个 JSON。但我不知道该怎么做,因为当我使用 @RequestParam("myObject") 而不是 @RequestBody 时,它不起作用。所以我的问题是:

如何通过一个 POST 请求传递 JSON 和其他参数(字符串、整数...等)?

最佳答案

1) 首先我建议您使用 Spring-Security。为了检查每个请求,spring中有一个注释@PreAuthorize,它将有助于在处理之前检查每个请求。

2)如果您想使用检查当前登录用户的用户名,则不需要传递两个参数。您可以使用以下代码检查当前登录用户。

    @PreAuthorize("isAuthenticated()") 
@RequestMapping(value = "/current", method = RequestMethod.GET)
public @ResponseBody Users getCurrentLoggedInUser() throws Exception {
Object authenticatorPrincipalObject = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String userName = null;
if(authenticatorPrincipalObject != null && authenticatorPrincipalObject instanceof Users){
Users authenticatorPrincipal = (Users) authenticatorPrincipalObject;
userName = authenticatorPrincipal.getUsername();
}else if(authenticatorPrincipalObject != null){
userName = authenticatorPrincipalObject.toString();
}else{
return null;
}
return userService.getCurrentLoggedInUser(userName);
}

3)我不认为在单个请求中我们可以同时传递 @RequestBody 和 @RequestParam 。 Spring MVC - Why not able to use @RequestBody and @RequestParam together

关于java - 使用 @RequestParam 发布 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27250286/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com