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

Wednesday, 5 June 2024

Implementing HTTP 301 URL Redirects in Spring Boot

 

301: Moved Permanently

The 301 status code indicates that the requested resource has been permanently moved to a new URI, and future references should use the provided new URI.

 

Clients which can update links should automatically update references to the old URI with the new ones returned by the server. The detailed steps look like below.

 

Step 1: Client Makes a Request

The client (e.g., a web browser) makes a request to access a resource at a specific URL.

 

Step 2: Server Responds with 301 Status Code

The server receives the request and responds with a 301 Moved Permanently status code. The response includes a Location header that specifies the new URI where the resource has been moved.

 

Step 3: Client Receives the Response

The client processes the server’s response and recognizes the 301 status code, indicating a permanent move.

 

Step 4:  Automatic Redirection

The client automatically follows the Location header and sends a new request to the specified new URI. This ensures the client retrieves the intended resource from its new location.

 

Step 5: Updating References

If the client has link editing capabilities (such as a browser with bookmarks or a web application with stored links), it should update its stored references.

a.   Bookmarks: The client should update any bookmarks that reference the old URI to point to the new URI.

b.   History: The client should update its browsing history to replace the old URI with the new URI.

c.    Internal Links: In the context of a web application, any internal links or references within the application should be updated to reflect the new URI.

 

Step 6: Future Requests

As client caches this old to new URL mapping in its internal cache, for subsequent requests to the old URI, the client will not send to the server for redirection URL, instead the request is automatically redirected to the new URL directly.

 


Sample response looks like below.

HTTP/1.1 301 Moved Permanently
Location: https://www.myanalytics.com
Content-Type: text/html; charset=UTF-8

To prevent unintended actions, automatic redirection of non GET/HEAD requests will be confirmed by the user. For example,

 

1.   A user submits a form (POST request) to http://mybank.com/trasfer-money.

2.   The server responds with a 301 status, redirecting to https://fakebank.com/transfer-money.

3.   If the browser automatically resends the POST request to the new URL without user confirmation, it might lead to unintended data submission or actions.

 

Follow below step-by-step procedure to build a working application.

 

Step 1: Create new maven project “permanent-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>permanent-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 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/"));
        return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
    }
}

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

Go to the location where pom.xml is located, and execute the command ‘mvn package’. Upon successful completion of the command, you can see a jar file ‘permanent-redirect-0.0.1-SNAPSHOT.jar’ located in target folder.

 

Run the Application

Execute below command to run the application.

java -jar ./target/permanent-redirect-0.0.1-SNAPSHOT.jar

Open the url "http://localhost:8080/api/redirect" in browser, you can see this is redirected to the url "https://self-learning-java-tutorial.blogspot.com". Response header looks like below.


 

Note

A 302 status code indicates a temporary redirect, so browsers do not cache the new URL. Instead, they always send requests to the server, which reads the new URL from the Location response header and redirects to it. For permanent moves, always use a 301 status code. In this case, browsers cache the response, reducing the load on the server.

You can download the application from this link


Previous                                                    Next                                                    Home

Building a POST API with Javalin: A Step-by-Step Guide

Using Javalin.post() method, we can define a POST api.

 

public Javalin post(@NotNull String path, @NotNull Handler handler)

Adds a POST request handler for the specified path to the instance.

 

public Javalin post(@NotNull String path, @NotNull Handler handler, @NotNull RouteRole... roles)

Adds a POST request handler with the given roles for the specified path to the instance. Requires an access manager to be set on the instance.

 

Example

javalin.post("/employees", (ctx) -> {
	EmployeeRequestDto employeeRequestDto  = ctx.bodyAsClass(EmployeeRequestDto.class);

	Map<String, Object> map = new HashMap<>();
	map.put("id", empIdCounter.getAndIncrement());
	map.put("name", employeeRequestDto.getName());
	map.put("age", employeeRequestDto.getAge());

	String respJson = JsonUtil.getJson(map);

	ctx.res().setHeader("Content-Type", "application/json");
	ctx.result(respJson).status(HttpStatus.CREATED);
});

Find the below working application.

 

Step 1: Create new maven project ‘javalin-post-api’.

 

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>javalin-post-api</artifactId>
	<version>1.0.0</version>

	<properties>
		<packaging>jar</packaging>
		<jdk.version>17</jdk.version>
		<release.version>17</release.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>io.javalin</groupId>
			<artifactId>javalin</artifactId>
			<version>5.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>2.0.3</version>
		</dependency>


		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.14.0</version>
		</dependency>

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.14.0</version>
		</dependency>


	</dependencies>

	<build>
		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.10.1</version>
				<configuration>
					<source>17</source>
					<target>17</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
				</configuration>
				<executions>
					<execution>
						<id>assemble-all</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

Step 3: Define JsonUtil class.

 

JsonUtil.java

package com.sample.app.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {

	public static String getJson(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		  return mapper.writeValueAsString(obj);
	}

}

Step 4: Define EmployeeRequestDto class.

 

EmployeeRequestDto.java

package com.sample.app.dto;

public class EmployeeRequestDto {

	private String name;
	private Integer age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

}

Step 5: Define main application class.

 

App.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.sample.app.dto.EmployeeRequestDto;
import com.sample.app.util.JsonUtil;

import io.javalin.Javalin;
import io.javalin.http.HttpStatus;

public class App {
	private static AtomicInteger empIdCounter = new AtomicInteger(1);

	public static void main(String[] args) {

		Javalin javalin = Javalin.create();

		javalin.get("/", (ctx) -> {
			ctx.result("Welcome to Javalin programming!!!!");
		});

		javalin.post("/employees", (ctx) -> {
			EmployeeRequestDto employeeRequestDto  = ctx.bodyAsClass(EmployeeRequestDto.class);

			Map<String, Object> map = new HashMap<>();
			map.put("id", empIdCounter.getAndIncrement());
			map.put("name", employeeRequestDto.getName());
			map.put("age", employeeRequestDto.getAge());

			String respJson = JsonUtil.getJson(map);

			ctx.res().setHeader("Content-Type", "application/json");
			ctx.result(respJson).status(HttpStatus.CREATED);
		});

		javalin.start(8080);
	}
}

Total project structure looks like below.



Build the project

Navigate to the folder, where pom.xml is located and execute the command ‘mvn package’.

 

Upon successful command execution, you can see a ‘javalin-post-api-1.0.0-jar-with-dependencies.jar’ file.

$ls ./target/
archive-tmp
classes
generated-sources
generated-test-sources
javalin-post-api-1.0.0-jar-with-dependencies.jar
javalin-post-api-1.0.0.jar
maven-archiver
maven-status
test-classes

Run the application

Execute below command to run the application.

 

java -jar ./target/javalin-post-api-1.0.0-jar-with-dependencies.jar

$java -jar ./target/javalin-post-api-1.0.0-jar-with-dependencies.jar 
[main] INFO io.javalin.Javalin - Starting Javalin ...
[main] INFO org.eclipse.jetty.server.Server - jetty-11.0.13; built: 2022-12-07T20:47:15.149Z; git: a04bd1ccf844cf9bebc12129335d7493111cbff6; jvm 17.0.5+9-LTS-191
[main] INFO org.eclipse.jetty.server.session.DefaultSessionIdManager - Session workerName=node0
[main] INFO org.eclipse.jetty.server.handler.ContextHandler - Started i.j.j.@30ee2816{/,null,AVAILABLE}
[main] INFO org.eclipse.jetty.server.AbstractConnector - Started ServerConnector@26a7b76d{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
[main] INFO org.eclipse.jetty.server.Server - Started Server@1fc2b765{STARTING}[11.0.13,sto=0] @916ms
[main] INFO io.javalin.Javalin - 
       __                  ___          ______
      / /___ __   ______ _/ (_)___     / ____/
 __  / / __ `/ | / / __ `/ / / __ \   /___ \
/ /_/ / /_/ /| |/ / /_/ / / / / / /  ____/ /
\____/\__,_/ |___/\__,_/_/_/_/ /_/  /_____/

       https://javalin.io/documentation

[main] INFO io.javalin.Javalin - Listening on http://localhost:8080/
[main] INFO io.javalin.Javalin - You are running Javalin 5.3.2 (released January 22, 2023).
[main] INFO io.javalin.Javalin - Javalin started in 549ms \o/

Open terminal and execute below curl command to test the post api.

curl --location --request POST 'http://localhost:8080/employees' \
--header 'Content-Type: application/json' \
--data-raw '{"name" : "Krishna", "age" : 32}'

$ curl --location --request POST 'http://localhost:8080/employees' \
> --header 'Content-Type: application/json' \
> --data-raw '{"name" : "Krishna", "age" : 32}'
{"name":"Krishna","id":1,"age":32}

You can download the application from this link.


 

Previous                                                    Next                                                    Home