Why java string method return null as string?

Viewed 265

This happened in a spring-boot application that used java version 1.8(java8). In a normal console application of java 14, it worked fine.

I had two methods related to a JWT filtering class which is extended by the "OncePerRequestFilter" class.

private String getJwt(HttpServletRequest request) {
    String authHeader = request.getHeader("Authorization");
    if (authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.replace("Bearer ", "");
    }

    return null;
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    try {
        String jwt = getJwt(request);
        if (!jwt.equals("null") && okenProvider.validateJwtToken(jwt)) {
            .....
            .....
        }
    } catch (Exception e) {
        ....
    }
    filterChain.doFilter(request, response);
}

expected jwt variable value was a token or null object. For checking that previously used jwt != null and that always gave true. It worked as expected when only changed that to !jwt.equals("null"). According to this, getJwt method always returns a String object even it is null. How can explain this? Is there a way to return a null value instead of "null"?

1 Answers

Actually, there was some mistake when debugging which caused to produce this problem as this way. For the login/sign-in request, frontend application has been passed the user credentials with Authentication header as Bearer null. Then the getJwt method is returned the sliced string of "null" to the other method. It was never executed the return null line.

Related