[英]Load web app (servlet on Tomcat) in a remote server
我開發了一個在本地計算機上運行的Web應用程序。 然后,我將戰爭文件加載到遠程服務器上的catalina主頁中。 Web應用程序可以運行,但是在嘗試連接到服務器上的數據庫時會停止。 該連接是localhost上的jbdc連接,數據庫是mysql。 當我在計算機上進行連接時,沒有出現問題。
String connectionString="jdbc:mysql://192.168.0.100:3306/"+request.getSession().getAttribute("dbname");
Connection con=null;
try {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response.sendRedirect("Errore.html");
return;
};
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con=(Connection) DriverManager.getConnection(connectionString,"root","root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection con為null,DriveManager.getConnection不起作用,我也不知道為什么。 我也嘗試使用postgresql連接,但問題是相同的。 我必須在遠程服務器中配置一些東西嗎? 服務器就像我的計算機一樣是debian 9.2。
我認為您需要將連接字符串定義為不是本地主機,而是完整的IP: String connectionString="jdbc:mysql://xx.xx.xx.xx:3306/"+request.getSession().getAttribute("dbname");
請嘗試以下代碼來測試連接。 它是一個Maven項目。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>my.test</groupId>
<artifactId>mavenproject2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
和src / main / java / App.java(請替換連接數據)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class App {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String host = "localhost";
String db = "mysql";
String user = "root";
String password = "root";
String connectionString = String.format("jdbc:mysql://%s:3306/%s", host, db);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(connectionString, user, password);
System.out.println("Everthing looks alright!");
}
}
如果編譯此項目,則將獲得mavenproject2-0.0.1-SNAPSHOT-jar-with-dependencies.jar將JAR上載到遠程系統並在此處嘗試
java -jar mavenproject2-0.0.1-SNAPSHOT-jar-with-dependencies.jar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.