Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Spring Boot Application - HttpServletResponse needed

I want the simplest spring boot application like...

@Path("/")
@Component
public class RestResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/hello")
    public String hello() {
        return "Hello World";
    }
}

I want to build a REST application and I need the HttpServletResponse because I want to check some conditions and then do a redirect for example.

@Context
private HttpServletResponse servletResponse;

...

if (...)
    servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    servletResponse.sendRedirect(...);
else
    servletResponse.setStatus(HttpServletResponse.XYZ);
    servletResponse.sendRedirect(...);

What is the best way to get the HttpServletResponse in a Spring Boot application?

like image 434
DaUser Avatar asked Sep 27 '26 21:09

DaUser


1 Answers

If you need HttpServletResponse the following will do.

@RequestMapping("/urlmapping") 
public String method(HttpServletResponse response){

  .....

  if (...)
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    response.sendRedirect(...);
  else
    response.setStatus(HttpServletResponse.XYZ);
    response.sendRedirect(...);

  .....

}

In the above example the HttpServletResponse object will be injected.

In the example I used @RequestMapping it should work for @Path also.

like image 79
Karthikeyan Vaithilingam Avatar answered Sep 29 '26 19:09

Karthikeyan Vaithilingam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!