Spring Controller redirect to another page

13,325

Solution 1

You are making asynchronous form submission using jquery ajax call. So, after your request is completed you need to change the document location using javascript. E.g., something like this:

$.ajax({
    type: "POST",
    url: document.getElementById("urltxt").value,
    data: parameters,
    complete: function() {
        window.location.replace(...);
      }
  });

Solution 2

It's not redirecting because you are submitting via ajax. You'll need to handle the redirect yourself. Perhaps this very popular question will help. How to manage a redirect request after a jQuery Ajax call

Share:
13,325
user1386375
Author by

user1386375

Updated on June 26, 2022

Comments

  • user1386375
    user1386375 about 2 years

    Hey I got the following problem. This is the content of the jspx file:

    function postSMTH() {
        $.ajax({
            type: "POST",
            url: document.getElementById("urltxt").value,
            data: parameters,
    
            });
    }
    
    <input type="hidden" value="${pageContext.request.contextPath}/foo/foo2/foodat" name="urltxt" id="urltxt"/>
    
    <div class="foodat"><a href="javascript:postSMTH();"><spring:message code="foo_foo2_foodat_text" text="FOODAT"/></a></div>
    

    So if I push the submit button, the postSMTH function is called and the ajax object is paste to the Controller which look like this:

    @Controller
    @RequestMapping(value="/foo")
    public class FooController {
    
    ..............
    
    @RequestMapping(value="/foo2", method=RequestMethod.POST)
    public String homePOST(HttpServletRequest request) {
        ........
    }    
    @RequestMapping(value="/foo2", method=RequestMethod.GET)
    public String homeGET(HttpServletRequest request) {
        ........
    } 
    
    
    @RequestMapping(value="/foo2/foodat", method=RequestMethod.POST)
    public String doTHAT(HttpServletRequest request) {
        //  check authorization
    
            Map fooMap = request.getParameterMap();
    
            // do something in the Database, depending on the paramMap
    
        return "redirect:/foo/foo1";
    }
    }
    

    Everything is working fine regarding the Database, but the Problem is, that the redirect at the end DOESN'T work. It just stays at the page foo2.

    I'm new to Spring, maybe its a little mistake somewhere. I just cant make it out by myself.

    Would be nice if someone would have some hint. Thanks

    • kosa
      kosa about 12 years
      Could be some exception happening and redirect not being called. Did you add log/System.out and see last statement is being called?
  • Eugene Kuleshov
    Eugene Kuleshov about 12 years
    In this case you should accept the answer or give some credit. Thanks