How to reset counter on zero on API controller

Viewed 59

I have an API that on each call return me a random document from MongoDB collection.

This is code:

AtomicInteger countSummerCamps = new AtomicInteger();

@GetMapping("/getRandomSummerCamps")
public String getRandomSummerCamps(Model model) {

    countSummerCamps.incrementAndGet();

    if (getCountSummerCamps() <= adventureHolidaysService.countAdventureHolidays("summerCamps")) {
        model.addAttribute("randomSummerCamps", adventureHolidaysService.findRandomAdventureHolidays("summerCamps"));

        return "randomSummerCamps";

    } else {

        return "noMoreDoc";
    }
}

What is my problem and how I tried.

So in this situation the program will return me four elements in HTML. And after that the program will show me a noMoreDoc page. That works fine. But the problem is when I refresh the page. It’s still page noMoreDoc even if I go on the home page and hit the API again. It’s still the noMoreDoc page. I want to avoid that and after the user refreshes the page and get back on /getRandomSummerCamps show the user random documents again on every call.

I tried to set counterSummerCamps.set(0) inside }else{, but I got "Unreachable statement".

Is there a way to fix this, so after the user got the noMoreDoc page and after the user get back on, to /getRandomSummerCamps show the user random documents again on each call?

1 Answers

If you call counterSummerCamps.set(0) after the return statement of else, you will get unreachable code. Try to set it before the return statement.

Related