Right now, I have a web application that returns a redirect response if certain conditions are met. That comes back to the browser as a 302 redirect. I would like it to be a 301 redirect instead.
I tried setting the status code in the response, but that did not work. Here is a pared down sample:
package com._3dmathpuzzles.www;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
@EnableScheduling
@ServletComponentScan
@SpringBootApplication
public class MathPuzzlesWebApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(MathPuzzlesWebApplication.class, args);
}
@GetMapping("/index.html")
public String index(Model model)
throws Exception {
return "index";
}
@GetMapping("/Play/redirect.html")
public String Play(Model model, HttpServletResponse response) throws Exception {
// Check if we have everything we need, if not return a redirect
// if( conditions ) {
response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());
return "redirect:/";
// }
// ... other code
}
}
There should be a way to do this, right?
As Doug Breaux stated in the comment above, this question https://stackoverflow.com/a/44233134/796761 gives a very easy answer.
I changed my code to this:
req.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE,HttpStatus.MOVED_PERMANENTLY);
return "redirect:/";
And it is working perfectly. Thanks Doug!