Issue
In learning about Spring MVC knowledge, there are some things about Spring return types that confuse me.
In this documentation: Mapping Requests With @RequestMapping they return appointments/new
and redirect:/appointments
.
Code
@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
What's is the main difference between these two return types? As I understand it, the first type returns as a forward action, but if I'm right, why do they also publish forward:/
as a return type ?
Solution
First one returns the view while the later redirects to another controller request mapped action. Lets have alook from the code itself.
@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
Here when the result have errors, it renders the view appointments/new
so that the user can enter the correct details and add the apppointment again. URL will not change in the browser
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
But here, when the results has no error, this controller action redirect the website to the URL /appointments. Check the web browser URL which is changed to the redirected URL
Regarding forward:
vs redirect:
Quoted from this Satckoverflow answer Why do we use redirect in Spring MVC
Using the redirect prefix in your controller will generate a HTTP response with the 302 status code and the location header pointing to the redirection URL. The browser will then redirect to that URL (model exposed in the first request will be lost, and the browser URL will be the second one).
Using the forward prefix, the forward will be done internally by the servlet, so there's no need of a second request (URL will remain the same). The forward prefix should only be used in requests that can be safely repeated by the browser. That's not the case when you send a form which changes the database state (reloading the browser will lead to duplicate submissions). In these cases you should use redirect and apply the POST-redirect-GET pattern.
Answered By - Faraj Farook
Answer Checked By - Mary Flores (JavaFixing Volunteer)