Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting from HttpServletRequest to WebRequest

I've generated a Spring Boot web application using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

Technologies used:

Spring Boot 2.0.0.M6 , Java 8, maven

I have this method in 1 of the class

private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                                                   boolean includeStackTrace) {

        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        return this.errorAttributes.getErrorAttributes(request, includeStackTrace)

    }

But I don't know how to cast from javax.servlet.http HttpServletRequest org.springframework.web.context.request.WebRequest

The method getErrorAttributes(WebRequest, boolean) in the type ErrorAttributes is not applicable for the arguments (HttpServletRequest, 
     boolean)
like image 954
en Lopes Avatar asked Nov 23 '17 12:11

en Lopes


People also ask

How do I get URI from WebRequest?

Casting WebRequest to ServletWebRequest solved the purpose. Instead of getRequestURL() , getRequestURI() be used to get the URI in the question.

What is WebRequest in Java?

public interface WebRequest extends RequestAttributes. Generic interface for a web request. Mainly intended for generic web request interceptors, giving them access to general request metadata, not for actual handling of the request.

How do I get HttpServletRequest in Webflux?

The code to get it is as follows. ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder. getRequestAttributes(); // get the request HttpServletRequest request = requestAttributes. getRequest();

How do I get HttpServletRequest in spring?

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder. getRequestAttributes()) . getRequest();


1 Answers

You don't need to cast HttpServletRequest to WebRequest. What you need is using WebRequest in your controller method.

@GetMapping("/endpoint")
public .. endpont(HttpServletRequest request, WebRequest webRequest) {
    getErrorAttributes(request, webRequest, true);
}

And change to your getErrorAttributes method

private Map<String, Object> getErrorAttributes(HttpServletRequest request, WebRequest webRequest,
                                               boolean includeStackTrace) {

    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace)

}
like image 58
shazin Avatar answered Oct 21 '22 14:10

shazin