Other than RedirectView , Spring provides another option to perform redirection: returning the redirected URL as a String with the prefix 'redirect:'."
The net effect is the same as if the controller had returned a RedirectView, but with this option the controller itself can simply operate in terms of logical view names.
The prefix 'redirect:' is a special directive for the view resolver to treat the returned string as URL redirection rather than as a view name.
A logical view name such as redirect:/some/resource will redirect relative to the current Servlet context, while a name such as redirect:http://www.example.com/path will redirect to an absolute URL.
The controller conditionally can return a view name or a redirected URL.
By default, status code 302 is sent. If we want to change that we can annotate the return type of handler method with @ResponseStatus(..).
The following example demonstrates the use of 'redirect:'
The Controller
In this example, if the path template variable 'id' consists of digits, it redirects to different URL otherwise it returns the error page view name.
package com.logicbig.example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import java.util.Map;
@Controller
public class MyController {
@RequestMapping(value = "test/{id}")
public String handleTestRequest (@PathVariable("id") String id,
Model model,
RedirectAttributes ra) {
if (!id.matches("\\d+")) {
model.addAttribute("msg", "id should only have digits");
return "error-page";
} else {
ra.addAttribute("attr", "attrVal");
return "redirect:/test2/{id}";
}
}
@RequestMapping("test2/{id}")
public String handleRequest (@PathVariable("id") String id,
@RequestParam("attr") String attr,
Model model) {
model.addAttribute("id", id);
model.addAttribute("attr", attr);
return "my-page";
}
}
my-page.jsp
src/main/webapp/WEB-INF/views/my-page.jsp<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
<p> id : ${id}</p>
<p> attr : ${attr}</p>
</body>
</html>
error-page.jsp
src/main/webapp/WEB-INF/views/error-page.jsp<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<body>
<p style="color:red;"> Error message : ${msg}</p>
</body>
</html>
Running Example
To try examples, run embedded Jetty (configured in pom.xml of example project below):
mvn jetty:run
Enter a valid URL e.g.
http://localhost:8080/spring-redirect-prefix/test/23
The URL in the address bar will change due to redirection
http://localhost:8080/spring-redirect-prefix/test2/23?attr=attrVal
Now enter an URL with invalid id, it will show the error page (no redirection will happen):
Integration Test
package com.logicbig.example;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import org.springframework.web.context.WebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
@SpringJUnitWebConfig(MyWebConfig.class)
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvcTester mockMvcTester;
@BeforeEach
public void setup() {
this.mockMvcTester = MockMvcTester.from(this.wac);
}
@Test
public void testController() {
assertThat(this.mockMvcTester.get().uri("/test/5")
.exchange())
.hasRedirectedUrl("/test2/5?attr=attrVal");
}
@Test
public void testController2() {
assertThat(this.mockMvcTester.get().uri("/test/a")
.exchange())
.model().containsEntry("msg", "id should only have digits");
assertThat(this.mockMvcTester.get().uri("/test/a")
.exchange())
.hasViewName("error-page");
}
}
mvn clean test -Dtest="ControllerTest" Output$ mvn clean test -Dtest="ControllerTest" [INFO] Scanning for projects... [INFO] [INFO] ------------< com.logicbig.example:spring-redirect-prefix >------------- [INFO] Building spring-redirect-prefix 1.0-SNAPSHOT [INFO] from pom.xml [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- clean:3.2.0:clean (default-clean) @ spring-redirect-prefix --- [INFO] Deleting D:\example-projects\spring-mvc\spring-redirect-prefix\target [INFO] [INFO] --- resources:3.3.1:resources (default-resources) @ spring-redirect-prefix --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-redirect-prefix\src\main\resources [INFO] [INFO] --- compiler:3.15.0:compile (default-compile) @ spring-redirect-prefix --- [INFO] Recompiling the module because of changed source code. [INFO] Compiling 3 source files with javac [debug target 25] to target\classes [INFO] [INFO] --- resources:3.3.1:testResources (default-testResources) @ spring-redirect-prefix --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-redirect-prefix\src\test\resources [INFO] [INFO] --- compiler:3.15.0:testCompile (default-testCompile) @ spring-redirect-prefix --- [INFO] Recompiling the module because of changed dependency. [INFO] Compiling 2 source files with javac [debug target 25] to target\test-classes [INFO] [INFO] --- surefire:3.2.5:test (default-test) @ spring-redirect-prefix --- [INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider [WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.logicbig.example.ControllerTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.034 s -- in com.logicbig.example.ControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 4.828 s [INFO] Finished at: 2026-08-06T21:36:58+08:00 [INFO] ------------------------------------------------------------------------ INFO: Completed initialization in 2 ms INFO: Completed initialization in 1 ms
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 3.2.9.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- spring-test 7.0.6 (Spring TestContext Framework)
- junit-jupiter-engine 6.0.3 (Module "junit-jupiter-engine" of JUnit)
- hamcrest 3.0 (Core API and libraries of hamcrest matcher framework)
- assertj-core 3.26.3 (Rich and fluent assertions for testing in Java)
- JDK 25
- Maven 3.9.11
|