JSON发布了@RequestParam

时间:2014-12-02 13:10:02

标签: java json rest spring-mvc post

在我的应用中,我有方法

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

如何使用 ONE POST请求传递JSON和其他参数(字符串,整数等)?

1 个答案:

答案 0 :(得分: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