Spring Boot

How to redirect in Spring Boot

Redirect in the Spring Boot framework

In this post I will show you how to redirect or direct the user to another URL within the method of a controller in the Spring Boot framework.

Redirecting to another URL in Spring Boot is very useful when the user does a certain action and we must return it to the main page.

Send to another route in Spring Boot

To make a redirect, simply create the method in the Controller and return a String.

Within the method, return a string with the following format:

redirect:/new_path/here

Example to redirect in Spring Boot

Let’s see a very simple example. I have my Spring Boot controller called ProductosController.java, inside it I must do a redirect within the method called guardarProducto.

To do this, I do the following:

@PostMapping(value = "/agregar")
public String guardarProducto(@ModelAttribute Producto producto) {
    productosRepository.save(producto);
    return "redirect:/productos/agregar";
}

On line 2 I define the method; It is very important to return a String.

Finally on line 4 we redirect to /productos/agregar using redirect:.

When the user calls that method, a redirect to that route will be done, after saving the Producto entity.

Important note:

Do not put the @ResponseBody annotation in the definition of your method, because if you do, the redirect will not work.


I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation

parzibyte

Freelancer programmer ready to work with you. Web, mobile and desktop applications. PHP, Java, Go, Python, JavaScript, Kotlin and more :) https://parzibyte.me/

Ver comentarios

Compartir
Publicado por
parzibyte
Etiquetas: spring boot

Entradas recientes

Receipt designer for thermal printers – Free and open source

In the last months I have been working on a ticket designer to print on…

12 months hace

JavaScript: store and read files with the Origin Private File System

In this post you will learn how to use the Origin Private File System with…

1 year hace

JavaScript: download file with fetch

In this post you will learn how to download a file in the background using…

1 year hace

SQLite3 with vanilla JavaScript and OPFS – Hello world

In this post I will show you how to use SQLite3 directly in the web…

1 year hace

Python Thermal Printing: A Comprehensive Guide for Printing on Thermal Printers

In this tutorial, we'll explore how to effortlessly print receipts, invoices, and tickets on a…

1 year hace

Image printing on Thermal printer

When printing receipts on thermal printers (ESC POS) sometimes it is needed to print images…

1 year hace

Esta web usa cookies.