Tomaž Bizjak
Tomaž Bizjak

Reputation: 65

How do I redirect users after successfully submitting form data?

I have a website through which you can create bundles and add custom or predefined tasks to them.

1]

Everything works okay, I can change all these fields whenever I want. Once all these fields look alright to you, you have to click the "Save" button. Once you click it, the fields are validated through several methods. If all the fields were validated successfully, Ajax sends a post request to my Spring controller which then stores everything into a database. After that, I would like to redirect user to the page which displays all the existing bundles.

enter image description here

I have already tried to do this:

@RequestMapping(value = "/bundle", method = RequestMethod.POST, consumes = {"application/octet-stream", "multipart/form-data"})
public void bundle(MultipartHttpServletRequest request,
                   HttpServletResponse response) throws IOException {

    // Code to store bundles to a database.

    // Redirect
    response.setHeader("Location", "http://localhost:8080/bundles");
    response.setStatus(302); //302 Found

    // I have also tried to replace above two statements with this
    response.sendRedirect("http://localhost:8080/bundles");
}

The above code does execute and the request is sent to /bundles

enter image description here

But I seem to be stuck on the initial page, no redirect was made.

Upvotes: 1

Views: 184

Answers (1)

Danilo Jakob
Danilo Jakob

Reputation: 81

I had the same problem as you have. I solved the issue by redirecting in the Front-End with Angular.

You can use the answer from your HTTP-Request in javascript and then redirect from there.

My Server-Side code:

@PostMapping(AdminToolConstants.MAPPING_CHECK_USER)
    public ResponseEntity checkUser(HttpServletResponse response, @RequestBody UserDto userDto) throws IOException{
        if (userService.checkUser(userDto)) {
            return new ResponseEntity(HttpStatus.OK);
        } else {
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
     }

Client-side javascript:

angular.module('admintool.services', []).factory('UserService', ["$http", "CONSTANTS", function($http, CONSTANTS) {
    var service = {};
    service.checkUser = function (userDto) {
        return $http.post(CONSTANTS.checkUser, userDto).then(function (value) {
                window.location.href = "/";
        }).catch(function (reason) { window.location.href = "/register" });
    };
    return service;
}]);

Inside .then I redirect the user when the, for example, login was successfull and inside .catch if the login wasn't successfull.

Upvotes: 1

Related Questions