java - 在实际 Web 请求之外引用请求属性时如何避免 IllegalStateException

标签 java spring spring-mvc

我正在研究一个解决方案,如果我正在处理 Web 请求,该解决方案应该执行某些操作,如果没有,则执行其他操作。

我在做的是

@Autowired private HttpServletRequest request;

然后尝试访问一个变量:

request.getRequestURI()

但是我得到了 java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside an actual web request...

我想避免异常,并以某种方式询问 HttpServletRequest 是否天气,我是否在 Web 请求中。

有什么办法吗?

例子: 附加信息:

@Override
public void trace(String msg) { 
    if (loggerFactory.isRegisteredUrl(request.getRequestURI())){
        loggerFactory.getCustomeLogger(request.getRequestURI()).trace(msg);
        return;
    }
    nativelogger.trace(msg);
}

最佳答案

您应该(未测试)使用 RequestContextHolder.getRequestAttributes() :

Return the RequestAttributes currently bound to the thread.

Returns: the RequestAttributes currently bound to the thread, or null if none bound

因此,如果该方法返回 null,则当前线程没有在处理请求。如果它返回一个非空值,它正在处理一个。

关于java - 在实际 Web 请求之外引用请求属性时如何避免 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19209356/

相关文章:

java - Gradle 无法解析 org.springframework.boot :spring-boot-gradle-plugin:1. 4.2.RELEASE (repo1.maven.org: Nome o servizio sconosciuto)

java - @ExceptionHandler 的顺序

java - 在 Spring MVC 中显式使用 POST 请求值

java - 如何在四个方向上扩展jScrollPane?

Java ArrayList Iterator next() 没有按预期工作

java - 使用 jdbc 驱动程序将 java 连接到 SQL Server

java - 在没有 key 的情况下从 Spring 从属性文件中读取值

java - 斯卡拉错误 : Could not find or load main class in both Scala IDE and Eclipse

java - Camel 属性-占位符 : Not able to configure `camel:sslContextParameters` with nested properties

java - 如何在 REST MVC Spring 测试中发出 POST 测试请求