Bozhidar Marinov
Bozhidar Marinov

Reputation: 126

On returning ModelAndView in Spring, the url is not changed

i am trying to understand why after returning new ModelAndView(), the url is not changed. Here is my code :

<div class="container" id="container">
   <button id="test1" onclick="showSchedule(this.id)">Test button</button>
</div>
<script>
  function showSchedule(buttonName) {
    $.ajax({
      url: "/appointment/employee/" + buttonName,
      type: "GET",
      dataType: 'html',
      success: function (response) {
        $("#container").html(response);
      },
      error: function (response) {
        console.log(response);
      }
    });
  }

Here is the controller that catch that request:

@RequestMapping("/appointment")
public class AppointmentController {

  @GetMapping(value = "/employee/{scheduleName}")
  public @ResponseBody
  ModelAndView showSchedule(@PathVariable("scheduleName") String scheduleName,
                            Model model,
                            HttpServletRequest request) throws IOException {
    model.addAttribute("scheduleName", scheduleName);
    ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
    String url = request.getRequestURL().toString();
    mav.addObject("url", url);
    mav.addObject("view", "renderAppointments");
    mav.setViewName("renderAppointments");
    return mav;
  }
}

In that case, the jsp is rendered but the url is not changed. If i change dataType to json, i receive all the needed information and can change the url, but then the jsp is not rendered

Upvotes: 0

Views: 373

Answers (1)

Marco Behler
Marco Behler

Reputation: 3724

You are doing an ajax call ($.ajax).

This won't change your URL, as it is an asynchronous Javascript call - so, expected behavior.

I don't know exactly what you are trying to do here, but this will work, without all your Javascript.

<form action="/appointment/employee/test1">
    <input type="submit" value="Test button" />
</form>

Upvotes: 1

Related Questions