Java web應用中如何判斷Web容器型別
阿新 • • 發佈:2019-01-29
問題背景:最近在開發一個人行的專案,由於不同的商行所使用的WEB容器不一樣,導致同樣的程式碼在不同的容器中執行的效果不一樣。因此想在程式碼中新增容器判斷,從而讓應用自動選擇不同的實現。
問題描述:開發階段使用的是jetty6,商行使用的應用伺服器有tomcat7、websphere application server8.5.5,JDK版本是1.6
解決方法:
1)在專案中引入portal-kernel.jar,pom.xml中新增如下程式碼:
2)程式碼如下:<!-- https://mvnrepository.com/artifact/com.liferay.portal/portal-kernel --> <dependency> <groupId>com.liferay.portal</groupId> <artifactId>portal-kernel</artifactId> <version>5.2.3</version> <scope>provided</scope> </dependency>
import com.liferay.portal.kernel.util.ServerDetector; /** * 該類用於獲取web容器的型別,如:tomcat、jetty、was、jboss等 * * @author wm */ public class WebContainerInfo { public static String getServerName() { String serverName = null; if (ServerDetector.isWebLogic()) { serverName = "WebLogic"; } else if (ServerDetector.isTomcat()) { serverName = "Tomcat"; } else if (ServerDetector.isWebSphere()) { serverName = "WebSphere"; } else if (ServerDetector.isSupportsComet()) { serverName = "SupportsComet"; } else if (ServerDetector.isResin()) { serverName = "Resin"; } else if (ServerDetector.isOC4J()) { serverName = "OC4J"; } else if (ServerDetector.isJOnAS()) { serverName = "JOnAS"; } else if (ServerDetector.isJetty()) { serverName = "Jetty"; } else if (ServerDetector.isJBoss()) { serverName = "JBoss"; } else if (ServerDetector.isGeronimo()) { serverName = "Geronimo"; } else if (ServerDetector.isGlassfish()) { serverName = "Glassfish"; } else if (ServerDetector.isGlassfish2()) { serverName = "Glassfish2"; } else if (ServerDetector.isGlassfish3()) { serverName = "Glassfish3"; } return serverName; } }