【问题标题】:JSON posted with @RequestParamJSON 与 @RequestParam 一起发布
【发布时间】:2015-01-30 18:01:06
【问题描述】:

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

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 服务,因此对于安全,我需要对每个请求进行身份验证,所以我还需要传递一个 USERNAME,而不仅仅是一个 JSON。但我不知道该怎么做,因为当我使用@RequestParam("myObject") 而不是@RequestBody 时,它就不起作用了。所以我的问题是:

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

【问题讨论】:

  • 为什么?您需要@RequestBody 用于 JSON 数据,@RequestParam 用于参数。
  • 但是我应该如何将 JSON 和其他参数传递给服务,以便 JSON 可以很好地转换为 java 中的对象?
  • 你最好设置 Spring Security 并使用过滤器来实现你的身份验证。
  • 好的,我是 Spring 新手,但我会阅读有关 Spring Security 的信息。此外,是否可以选择在一个 POST 请求中发送 JSON 和例如字符串?

标签: java json rest spring-mvc post


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-10-11
    • 1970-01-01
    • 2016-11-10
    • 2017-12-20
    • 2012-11-22
    • 2013-09-19
    • 2019-03-31
    相关资源
    最近更新 更多