Thursday, 6 June 2024

Implementing HTTP 302 URL Redirects using spring boot

302: Moved Temporarily

The HTTP status code 302 indicates that the requested resource has been temporarily moved to a different URI. The client should continue to use the original Request-URI for future requests, as the redirection might change over time.

 

When an HTTP response with status code 302 (Found) is sent by the server, it might include instructions for caching. Caching is a mechanism used to store copies of web resources for later reuse, which can improve performance and reduce server load by reducing the need for repeated requests for the same resource.

 

Following step-by-step procedure helps you to understand temporary redirects better.

 

Step 1: Client sends a GET request to the original resource.

 

Step 2: Server responds with a 302 Found status and a Location header pointing to the new resource.

 

Step 3: Client processes the response. It sees the new URL in the Location header. It also checks the Cache-Control and Expires headers to determine caching behavior.

 

Step 4: Client sends a GET request to the new resource.

 

Same behavior is depicted in the below image.

 


Example Response Headers

HTTP/1.1 302 Found
Date: Fri, 05 Jun 2024 12:00:00 GMT
Server: ExampleServer/1.0
Location: http://example.com/new/resource
Cache-Control: max-age=3600, public
Expires: Fri, 05 Jun 2024 13:00:00 GMT
Content-Length: 154
Content-Type: text/html

a.   Status Line: HTTP/1.1 302 Found indicates that the requested resource has been temporarily moved.

b.   Date: The Date header indicates the date and time when the response was generated.

c.    Server: Indicates the server software and version.

d.   Location: Specifies the new URI where the resource has been temporarily moved.

e.   Cache-Control: Indicates caching directives. In this example, max-age=3600 specifies that the response can be cached for up to 3600 seconds (1 hour), and public indicates that the response can be cached by any cache, including proxy servers.

f.     Expires: Specifies the date and time at which the cached response expires. In this example, the response will expire at Fri, 05 Jun 2024 13:00:00 GMT.

g.   Content-Length: Indicates the size of the response body in bytes.

h.   Content-Type: Specifies the MIME type of the response body, in this case, text/html.

i.     Response Body: Contains a simple HTML document with a short message informing the client about the redirection and providing a hyperlink to the new URI.

 

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user.

 

Why manual confirmation is needed?

Methods other than GET and HEAD usually change the state of the resource on the server. Automatic redirection in these cases might result in unintended consequences. For example, automatically redirecting a DELETE request could accidentally delete a resource at the new URI.

 

Follow below step-by-step procedure to build the working application for temporary redirects.

 

Step 1: Create new maven project "temporary-redirect".

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample.app</groupId>
    <artifactId>temporary-redirect</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.2</version>
    </parent>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.0.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Step 3: Define RedirectController class.

 

RedirectController.java

package com.sample.app.controller;

import java.net.URI;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class RedirectController {

    @GetMapping("/redirect")
    public ResponseEntity<Void> redirect() {
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create("https://self-learning-java-tutorial.blogspot.com/"));

        // Set Cache-Control header to cache the response for 1 hour (3600 seconds)
        headers.setCacheControl("max-age=3600, public");

        // Set Expires header to 1 hour from now
        ZonedDateTime expiresAt = ZonedDateTime.now().plusHours(1);
        String expires = DateTimeFormatter.RFC_1123_DATE_TIME.format(expiresAt);
        headers.set("Expires", expires);

        return new ResponseEntity<>(headers, HttpStatus.FOUND); // Use HttpStatus.FOUND (302) for temporary redirect
    }
}

Step 4: Define main application class.

 

App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}

Build the project

Navigate to the folder where pom.xml is located and execute below command.

 

mvn package

 

Upon successful execution of the command, you can see a jar file ‘temporary-redirect-0.0.1-SNAPSHOT.jar’ in the target folder.

 

Run the application

Execute the command ‘java -jar ./target/temporary-redirect-0.0.1-SNAPSHOT.jar’ to run the application.

 

Open the url 'http://localhost:8080/api/redirect' to observer the behavior.

$ curl --head http://localhost:8080/api/redirect
HTTP/1.1 302 
Location: https://self-learning-java-tutorial.blogspot.com/
Cache-Control: max-age=3600, public
Expires: Wed, 5 Jun 2024 21:13:46 +0530
Content-Length: 0
Date: Wed, 05 Jun 2024 14:43:46 GMT

You can download the application from this link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment