java 如何为每个API调用初始化一个布尔变量?

vqlkdk9b  于 2022-12-25  发布在  Java
关注(0)|答案(2)|浏览(351)

我有一个API

public interface UserService{

@GetMapping("/get-user-data")
public Response getUserData();

}

我有我的impl如下

public class UserServiceImpl implements UserService{

private boolean isAuthorized = false;

public Response getUserData(User user){
    //check if user is authorized
    isAuthorized = isUserAuthorized()?true:false;
    //perform other things based on above boolean
    return someResponse;
    }
}

我想这个布尔“isAuthorized”必须设置为假的每一个调用这个API。无论我有以上是不工作,如何实现这一点?

4jb9z9bj

4jb9z9bj1#

我们通常不跟踪布尔变量的状态,而是根据肯定条件执行一些操作:

public Response getUserData(User user){
    if (isUserAuthorized()) {
        // actions that should happen only when authorized
    } else {
        // actions that should happen only when NOT authorized 
    }
}

但是如果你真的想跟踪那个状态,你可以在方法调用结束时将变量设置为false:

//check if user is authorized
isAuthorized = isUserAuthorized()?true:false;
//perform other things based on above boolean
isAuthorized = false;
return someResponse;

注意:这可能会导致与并发性相关的问题,但如果这与您无关,也没有什么坏处。

f87krz0w

f87krz0w2#

如果你想为所有的API方法调用一个业务逻辑方法,你需要使用一个web HandlerInterceptor,例如:

@Component
public class AppInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(AppInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        var authorized = UserIsAuthorizedDummy(); // <- you business logic here
        request.setAttribute("is_authorized", authorized);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {}

    private boolean UserIsAuthorizedDummy() {
        return true;
    }
}

并使用WebMvcConfigurer实现配置此拦截器,例如:

@Configuration
public class AppConfig implements WebMvcConfigurer {
    @Autowired
    AppInterceptor appInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(appInterceptor);
    }
}

然后你可以在你的控制器方法中使用它,你将看到并访问来自请求对象的is_authorized属性。示例:

@GetMapping("/user")
    public LocalResponse getUser(HttpServletRequest request) {
        var response = new LocalResponse();
        // check AppInterceptor.preHandle() to see when "is_authorized" attribute is set
        response.setAuthorized((boolean) request.getAttribute("is_authorized"));

        if (response.isAuthorized()) {
            response.setUserId("1111");
        }

        return response;
    }

    @GetMapping("/profile")
    public LocalResponse getProfile(HttpServletRequest request) {
        var response = new LocalResponse();
        // check AppInterceptor.preHandle() to see when "is_authorized" attribute is set
        response.setAuthorized((boolean) request.getAttribute("is_authorized"));

        if (response.isAuthorized()) {
            response.setUserId("1111-22222");
        }

        return response;
    }

您可以在以下存储库中看到一个工作示例:https://github.com/eriknyk/springboot-web-interceptor-demo/

相关问题