Question

I need to input URL like this http://localhost:8080/first and after that my controller must go to http://localhost:8080/second and so on until I came to http://localhost:8080/end. Its something like recursion. At the end point I need to pring a list.

@Controller
@RequestMapping(value = "/", method = RequestMethod.GET)
public class CascadeController {    
    @RequestMapping("/first")
    String first(ModelMap model) {
        model.put("list", new ArrayList<String>());
        return "/second";
    }

    @RequestMapping("/second")
    String second(ModelMap model) {
        ((List) model.get("list")).add("A");
        return "/third";
    }

    @RequestMapping("/third")
    String third(ModelMap model) {
        ((List) model.get("list")).add("B");
        return "end";
    }
}

end.jsp

<%@ page import="java.util.List" %>
<html>
<body>
   <%for(String s : (List<String>) request.getAttribute("list")){%>
      <%=s%>
   <%}%>
</body>
</html>

Is anybody can explain what is wrong with my code?

Was it helpful?

Solution

Does the user need to see the data placed on the model for the /first or /second page? If not, how about try changing:

return "/second"; to return "redirect:/second";

and

return "/third"; to return "redirect:/third";

If the user needs to see the data on /first or /second page for X time, how about doing the redirect from javascript?

Edited: How about flash attributes, see this post: reading flash attributes

  @RequestMapping("/first")
    String first(ModelMap model, final RedirectAttributes redirectAttributes) {
        model.put("list", new ArrayList<String>());
        redirectAttributes.addFlashAttribute("list", new ArrayList<String>());
        return "redirect:/second";
    }

    @RequestMapping("/second")
    String second(ModelMap model, final RedirectAttributes redirectAttributes) {
        List list = (List) model.get("list");
        list.add("A");
        redirectAttributes.addFlashAttribute("list", list);
        return "redirect:/third";
    }

    @RequestMapping("/third")
    String third(ModelMap model, final RedirectAttributes redirectAttributes) {
        List list = (List) model.get("list");
        list.add("B");
        redirectAttributes.addFlashAttribute("list", list);
        return "end";
    }

OTHER TIPS

I suggest that you take a look at Spring Webflow. Copied from the project description:

The sweet spot for Spring Web Flow are stateful web applications with controlled navigation [...] these scenarios have in common is one or more of the following traits:

  • There is a clear start and an end point.
  • The user must go through a set of screens in a specific order.
  • The changes are not finalized until the last step.
  • Once complete it shouldn't be possible to repeat a transaction accidentally
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top