Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of springboot Redirection

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the example analysis of springboot redirection for you. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Notes on springboot redirection (redirect prefix)

@ ModelAttribute: read the data in modelAndView

@ Target ({ElementType.PARAMETER, ElementType.METHOD}) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface ModelAttribute {@ AliasFor ("name") String value () default "; @ AliasFor (" value ") String name () default"; boolean binding () default true;} example @ RestControllerpublic class Hello3Controller {@ RequestMapping ("/ hello2") public ModelAndView hello2 () {ModelAndView mv=new ModelAndView (); mv.setViewName ("redirect:/redirect2") Mv.addObject ("attributeName", "King of the Thief"); Person person=new Person (); person.setName ("Guatian Li Xia"); person.setAge (20); mv.addObject ("person", person); return mv } @ RequestMapping ("/ redirect2") public String redirect2 (String attributeName,@ModelAttribute ("attributeName") String name,Person person,ModelAndView mv) {System.out.println (attributeName+ "" + name); System.out.println (person); System.out.println (mv.getModelMap (). GetAttribute ("attributeName")); return "redirect2";}}

Console output

The king of sea thieves

Person (name=null, age=null)

Null

Note: get the data directly in the method body, and the parameters can be mapped automatically, or you can use @ ModelAttribute to get the data. This method can only pass strings, but not pojo objects.

Why should the Spring redirect (Redirect) guide be redirected?

Let's first consider the reasons why you might need to do a redirection in a Spring application.

Of course, there are many possible examples and reasons. A simple one might be the POST form data, which revolves around the problem of double submission, or simply delegates the execution flow to another controller method.

As a note, the typical Post / Redirect / Get pattern does not fully solve the double commit problem-the problem of refreshing the page before the initial commit is completed may still lead to double submission.

Redirect using RedirectView

Let's start with this simple method-let's just take an example:

Behind the scenes, RedirectView triggers HttpServletResponse.sendRedirect ()-which performs the actual redirection.

Notice how we inject redirect properties into the method-the framework does this heavy work, allowing us to interact with these properties.

We add attribute to the model RedirectAttributes-exposing it as a HTTP query parameter (Query parameter). The model contains objects-usually strings or objects that can be converted to strings.

Now let's test our redirect function-using a simple curl command to help:

The result will be:

Redirect using the redirect: prefix

The previous method uses RedirectView because it is not optimal for some reasons.

First of all, we are now coupled to Spring API because we use RedirectView directly in our code.

Second, we need to know from the beginning that when implementing a controller operation, its results will always be redirected, but this is not always the case.

A better option is to use the redirect: prefix-- the redirected view name is injected into the controller like any other logical view name. The controller doesn't even know that redirection is happening.

It looks like this:

When the view name is returned with redirect:, the UrlBasedViewResolver class (and all its subclasses) recognizes it as a special indication that needs to be redirected. The rest of the view name is treated as a redirect URL.

There is one thing to note here-when we use the redirect:/redirectedUrl logical view here, we are doing a redirection that is relevant to the current Servlet context.

If we need to redirect to an absolute URL, we can use a name like this: redirect: http://localhost:8080/spring-redirect/redirectedUrl.

So now, when we execute the curl command:

We'll get a redirect right away:

Forward using the forward prefix

Now let's see how to do something slightly different-- a retweet.

Before we look at the code, let's take a look at a quick, high-level summary of the semantics of forwarding and redirection:

The redirection will respond with a new URL containing the 302 response code and location header; then the browser / client will make a request to the new URL again

Forwarding occurs entirely on the server side; the Servlet container forwards the same request to the URL in the target URL; browser without change

Now let's look at the code:

Like redirect:, the forward: prefix will be parsed by UrlBasedViewResolver and its subclasses. Internally, this creates an InternalResourceView that performs a RequestDispatcher.forward () operation for the new view.

When we execute this command with curl:

We will get HTTP 405 (disallowed method):

Compared to our two requests in the redirect solution, in this case, we have only one request sent from the browser / client to the server. Of course, attributes previously added by redirects are no longer needed.

Contains the properties of RedirectAttributes

Next-- let's look at passing attributes in a redirect-- take full advantage of RedirectAttribures in the framework:

As mentioned earlier, we can insert property objects directly into the method-which makes this mechanism very easy to use.

Also notice that we also add a Flash attribute-an attribute that will not be added to the URL. We can do this through this property-- we can later access the flash property using @ ModelAttribute ("flashAttribute") in the method of the final target of the redirection:

So, get it done-- if you need to use curl to test this feature:

We will be redirected to a new location:

In this way, using RedirectAttribures instead of ModelMap gives us the ability to share only some properties between the two methods involved in the redirect operation.

Another configuration without a prefix

Now let's explore another configuration-- redirection without a prefix.

To do this, we need to use org.springframework.web.servlet.view.XmlViewResolver:

Instead of the org.springframework.web.servlet.view.InternalResourceViewResolver we used in the previous configuration:

We also need to define a RedirectView bean in the configuration:

Now we can trigger the redirection by referencing this new bean through id:

To test it, we use the curl command again:

The result will be:

Redirect HTTP POST request Request

For use cases such as bank payments, we may need to redirect the HTTP POST request. Depending on the returned HTTP status code, the POST request can be redirected to HTTP GET or POST.

According to the HTTP 1.1 protocol reference, status codes 301 (permanently removed) and 302 (found) allow the request method to be changed from POST to GET. The specification also defines related 307 (temporary redirection) and 308 (permanent redirect) status codes that do not allow the request method to be changed from POST to GET.

Now, let's look at the code that redirects the post request to another post request:

Now, let's test the redirected POST using the curl command:

We are being redirected to the destination address:

This is the end of this article on "sample analysis of springboot redirection". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report