What is the difference between return "view" and return "redirect: view" in a POST method for Spring MVC?

2

What happens is that I have a jsp view from which I fill a form, I send the data by means of the POST method to my controller and once the instructions are finished I return to the main view of my site. However, the methods contained in my driver GET for the main view did not start, returning the same completely clean without information, this using return"vista.jsp";

Now using return:"redirect:vista.jsp" my methods are on wheels returning the information, I managed to solve my error but I want to understand their difference well and be somewhat confused.

    
asked by Max Sandoval 24.02.2016 в 18:49
source

2 answers

2

What happens in your application is:

When you execute return"vista.jsp" you return to the browser the jsp, I guess when you say

  

returning the same completely clean without information

Is that you have a controller that handles the request of the user and puts information in your vista.jsp , but this controller that samples does not have that logic, that's why it goes "empty"

When you do a redirect:

It starts a request by the browser to your url, so the associated controller can load the information, because at this time if you are entering the game

Small outline of both cases

answered by 24.02.2016 / 18:56
source
3

If you use return "vista"; the server will make a forward to the view. If you use return "redirect:vista"; the server will perform a redirect to the url associated with the view. With this in mind, your question translates into what differences there are between a forward and a redirect. These concepts are not associated with Spring but with the development of Web applications in Java.

Forward

Your request will return a response with code 200, 201 or another, for example 500 if an error occurs during the attention of the request. In this case, the content of the response will be the content of your view, that is, your JSP. The benefits are that the attributes placed in the request scope can be reused for use in the rendering of the view. That is, by using Forward you can do this:

Code in the controller:

public String ejecutaPost(Model model) {
    model.add("saludo", "hola mundo!");
    return "vista";
}

Code in the view (usually JSP):

<p>El servidor manda un saludo: ${saludo}</p>

Redirect

Your request will return a response with HTTP code 300 indicating that the client (the browser) has to make a new request to another url of the server (or perhaps from an external server). The server will receive this request and will attend to it.

In this case, the attributes placed at the request level can not be exploited because a new request-response cycle is generated towards the server.

    
answered by 24.02.2016 в 18:52