如何在Spring中将变量从一个控制器传递给另一个控制器

时间:2019-04-16 06:14:05

标签: java spring oauth-2.0 controller

我能够从本地服务器获取访问令牌,但需要使用从注册后控制器中的注册get控制器检索到的访问令牌。如何将“ token”变量放入注册后控制器中以用于HTTP调用?

// Initial mapping for visiting the form
    @RequestMapping(value = "/signup", method= RequestMethod.GET)
    public String signupForm(@RequestParam("code") String code, @ModelAttribute("signup") emailInput form)
            throws JsonProcessingException, IOException {
            ResponseEntity<String> response = null;
            System.out.println("Authorization Code: " + code);

            RestTemplate restTemplate = new RestTemplate();

// Client id and secret replaced
            String credentials = "clientId:clientSecret";
            String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));

            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            headers.add("Authorization", "Basic " + encodedCredentials);

            HttpEntity<String> request = new HttpEntity<String>(headers);

            String access_token_url = "https://idfed.constantcontact.com/as/token.oauth2";
            access_token_url += "?code=" + code;
            access_token_url += "&redirect_uri=http://localhost:8080/signup";
            access_token_url += "&grant_type=authorization_code";

            response = restTemplate.exchange(access_token_url, HttpMethod.POST, request, String.class);

            System.out.println("Full Access Token Response: " + response.getBody());

            // Get the Access Token From the recieved JSON response
            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readTree(response.getBody());
            String token = node.path("access_token").asText();
            System.out.println("Here is my token: " + token);

        return "/signup";
    }

    // What happens after the user presses the submit button

第二个控制器,我需要在调用中使用变量。我在这里需要它,以便我可以使用从HTML页面收集的表单变量在用户发布表单数据后进行调用。

    @RequestMapping(value = "/signup", method= RequestMethod.POST)
    public String signupSubmit(@ModelAttribute("signup") emailInput form, RedirectAttributes redirectAttributes)
            throws IOException {
    // Use access token here to make calls to endpoints
        redirectAttributes.addFlashAttribute("email", form.getEmail());
        return "redirect:/result";
    }

0 个答案:

没有答案