Oscar Moncayo
Oscar Moncayo

Reputation: 188

Spring: Redirect depending the view

I have 2 indentical forms (View A and View B) that use the same controller. I would like it when I do the post of view A, redirect me to a url x and when I do post view B redirects me to another url (y). Is this possible in this function

@RequestMapping(value = "/panics/closeCase", method = RequestMethod.POST)
public String closeCase(@ModelAttribute("closeCaseFrom") CloseCaseFrom closeCaseFrom, Model model) {

    CloseCaseFrom sendCloseCaseFrom = new CloseCaseFrom();
    sendCloseCaseFrom.setDetail(closeCaseFrom.getDetail());
    sendCloseCaseFrom.setIdCasePanic(closeCaseFrom.getIdCasePanic());
    sendCloseCaseFrom.setIdPanic(closeCaseFrom.getIdPanic());
    sendCloseCaseFrom.setIdCasePanic(closeCaseFrom.getIdCasePanic());
    sendCloseCaseFrom.setIdStaff(user.getIdStaff());
    sendCloseCaseFrom.setIdUserSession(user.getIdUser());
    sendCloseCaseFrom.setSessionToken(user.getToken());

    panic.mClosePanicCase(sendCloseCaseFrom);


    return "redirect:/alerts";

}

How can I know, which view trigger the controller?

Upvotes: 0

Views: 90

Answers (1)

Boban Talevski
Boban Talevski

Reputation: 153

You could add a hidden input element in each view with the same name but a different value. You then get that value in your controller and redirect based on that.

This input is in ViewA

<input type="hidden" name="destination" value="a" />

This input is in ViewB

<input type="hidden" name="destination" value="b" />

And in your controller

@RequestMapping(value = "/panics/closeCase", method = RequestMethod.POST)
public String closeCase(@RequestParam destination, @ModelAttribute("closeCaseFrom") CloseCaseFrom closeCaseFrom, Model model) {

    //..
    if (destination.equals("a")) {
        // a goes to urlx
        return "redirect:/urlx";
    if (destination.equals("b")) { // or just else {
        // b goes to urly
        return "redirect:/urly";

}

Or instead of values a or b you could have the actual destination as a value in the input fields and avoid using if, just plug that destination in your redirect.

Upvotes: 1

Related Questions