Home > Software engineering >  is it possible to translate ServerHttpRequest and HttpServletRequest each other
is it possible to translate ServerHttpRequest and HttpServletRequest each other

Time:09-21

I am now using spring cloud gateway, from the spring could gateway filter I could get the ServerHttpRequest which come from org.springframework.http.server like this:

ServerHttpRequest request = (ServerHttpRequest) exchange.getRequest();

but the public library function just only accept HttpServletRequest which was in the package javax.servlet.http, is it possible to translate the two type of object? or must I write a overload function with different type of parameter? should I implement twice with the same function? BTW, this is my public function:

public static void handleLoginCheck(HttpServletRequest httpServletRequest) {
    AutoHeaderInfoRequest autoHeaderInfoRequest = AuthUtil.getAutoHeaderInfoRequest(httpServletRequest);
    if (autoHeaderInfoRequest.getAccessToken() == null) {
        throw ServiceException.NOT_LOGGED_IN_EXCEPTION;
    }
    if (!AuthUtil.verifyAccessToken(autoHeaderInfoRequest.getAccessToken())) {
        throw GlobalException.ACCESS_TOKEN_INVALID_EXCEPTION;
    }
    setRequestGlobalHeader(autoHeaderInfoRequest);
}

this function and all invoked function use HttpServletRequest.

CodePudding user response:

According to Spring Docs :

ServerHttpRequest interface implementation is based on HttpServletRequest interface.

Now, there is a class called ServletServerHttpRequest which implements the ServerHttpRequest interface and it also has the public method getServletRequest() to get the actual HttpServletRequest.

Change your implementation to this :

if(exchange.getRequest() instanceof ServletServerHttpRequest) {
   ServletServerHttpRequest request = (ServletServerHttpRequest) exchange.getRequest();
   HttpServletRequest httpServletRequest = request.getServletRequest();
}  

Refer docs for more.

  • Related