Spring Boot - 在不使用RedirectAttributes的情况下从另一个控制器调用控制器

时间:2017-11-24 16:39:06

标签: java spring redirect spring-boot

我想做什么:

在用户执行特定操作后向管理员发送推送通知。

问题:

如果我使用RedirectAttributes,我需要返回一个字符串值来调用另一个端点,但我还需要向用户返回一个http响应和一个模型。所以我想知道是否有另一种方法可以调用另一个端点,或者使用RedirectAttributes这样做的正确方法是什么。

@GetMapping("get_admin")
public ResponseEntity<Admin> getAdminById(@RequestHeader("lang") String locale,
                                          @RequestParam("id") Integer id,
                                          RedirectAttributes redirectAttrs) throws EntityNotFoundException {
    Admin admin = adminService.getAdminById(id);
    if (admin == null) {
        return new ResponseEntity(new ResponseAdmin(new LangString().getNoSuchAnAdmin(locale),"0"), HttpStatus.OK);
    }

    redirectAttrs.addFlashAttribute("locale",locale);
    redirectAttrs.addFlashAttribute("opType","0");
    redirectAttrs.addFlashAttribute("message","message");
    redirectAttrs.addFlashAttribute("type","type");
    redirectAttrs.addFlashAttribute("data","data");

    return new ResponseEntity(new ResponseAdmin(admin), HttpStatus.OK); 
    >>> I can't write "return redirect:/push_call;" since return type must be ResponseEntity, not String.
}

@GetMapping("push_call")
public ResponseEntity<String> redirectedPush(Model model){

    int opType = (int) model.asMap().get("opType");;
    String locale = (String) model.asMap().get("locale");;

    String messageStr = (String) model.asMap().get("message");;
    String dataStr = (String) model.asMap().get("data");;
    String typeStr = (String) model.asMap().get("type");;

    JSONObject body = new JSONObject();
    body.put("to", "XXXXXX");

    HttpEntity<String> request = new HttpEntity<>(body.toString());

    CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);

    try {
        String firebaseResponse = pushNotification.get();
        return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }

    return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
}

1 个答案:

答案 0 :(得分:0)

只需return redirectedPush(model)然后