Skip to content

Commit d20dabf

Browse files
committed
Fix issue with obtaining WebSocketContainer
1 parent d5a5a48 commit d20dabf

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

spring-websocket/src/main/java/org/springframework/web/socket/server/endpoint/ServerEndpointExporter.java

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@
3535
import org.springframework.context.ApplicationContext;
3636
import org.springframework.context.ApplicationContextAware;
3737
import org.springframework.util.Assert;
38-
import org.springframework.util.ClassUtils;
3938
import org.springframework.util.ReflectionUtils;
4039

4140
/**
@@ -58,9 +57,6 @@
5857
*/
5958
public class ServerEndpointExporter implements InitializingBean, BeanPostProcessor, ApplicationContextAware {
6059

61-
private static final boolean isServletApiPresent =
62-
ClassUtils.isPresent("javax.servlet.ServletContext", ServerEndpointExporter.class.getClassLoader());
63-
6460
private static Log logger = LogFactory.getLog(ServerEndpointExporter.class);
6561

6662

@@ -103,20 +99,25 @@ public void setApplicationContext(ApplicationContext applicationContext) {
10399
}
104100

105101
protected ServerContainer getServerContainer() {
106-
if (isServletApiPresent) {
107-
try {
108-
Method getter = ReflectionUtils.findMethod(this.applicationContext.getClass(), "getServletContext");
109-
Object servletContext = getter.invoke(this.applicationContext);
110102

111-
Method attrMethod = ReflectionUtils.findMethod(servletContext.getClass(), "getAttribute", String.class);
112-
return (ServerContainer) attrMethod.invoke(servletContext, "javax.websocket.server.ServerContainer");
113-
}
114-
catch (Exception ex) {
115-
throw new IllegalStateException(
116-
"Failed to get javax.websocket.server.ServerContainer via ServletContext attribute", ex);
117-
}
103+
Class<?> servletContextClass;
104+
try {
105+
servletContextClass = Class.forName("javax.servlet.ServletContext");
106+
}
107+
catch (Throwable e) {
108+
return null;
109+
}
110+
111+
try {
112+
Method getter = ReflectionUtils.findMethod(this.applicationContext.getClass(), "getServletContext");
113+
Object servletContext = getter.invoke(this.applicationContext);
114+
Method attrMethod = ReflectionUtils.findMethod(servletContextClass, "getAttribute", String.class);
115+
return (ServerContainer) attrMethod.invoke(servletContext, "javax.websocket.server.ServerContainer");
116+
}
117+
catch (Exception ex) {
118+
throw new IllegalStateException(
119+
"Failed to get javax.websocket.server.ServerContainer via ServletContext attribute", ex);
118120
}
119-
return null;
120121
}
121122

122123
@Override

0 commit comments

Comments
 (0)