Create a simple Java web application using WebApps
Improve security by including connection information to DB (SQLDatabase) in the connection string of WebApps without entering the password directly in the code
Select and create Web Apps from App Service
Select "Application Settings" of the created WebApps, and in "General Settings" Select any setting for Java version, Java minor version, Java web container
Select "Application Settings" of the created WebApps, and select "Connection String". Enter the connection string name, value, and type
Get the connection information earlier by getting environment variables (System.getenv) in the app
** System.getenv ("SQLCONNSTR_connection string name") **, if SQL Server is selected as the type If you select SQL Azure, get the value with ** System.getenv ("SQLAZURECONNSTR_connection string name") **
Also, store the SQL Server JDBC driver under WebContent / WEB-INF / lib. (https://docs.microsoft.com/ja-jp/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-2017)
Below is a simple sample code
package servlet;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.DriverManager;
public class SQLExecution {
//Get values from WebApps environment variables
String hostName = System.getenv("SQLCONNSTR_serverId"); // update me
String dbName = System.getenv("SQLAZURECONNSTR_dbId"); // update me
String user = System.getenv("SQLCONNSTR_useId"); // update me
String password = System.getenv("SQLCONNSTR_pass"); // update me
String url = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;encrypt=true;"
+ "hostNameInCertificate=*.database.windows.net;loginTimeout=30;", hostName, dbName, user, password);
Connection connection = null;
String sql = null;
void select() {
}
public void insert() {
try {
//Specify JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url);
// Create and execute a SELECT SQL statement.
sql = "insert into testTBL("
+ "key"
+ ")"
+ "Values"
+ "("
+ 1
+ ")";
try (Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql)) {
connection.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Deploy your app to Web Apps There are several methods, but this time Azure Toolkit for Eclipse (https://docs.microsoft.com/ja-jp/java/azure/eclipse/azure-toolkit-for-eclipse-installation?view=azure-java- stable) is used
Right-click on the app, select "Azure" <"Publish AS Azure Web Apps", and select the Web Apps you want to deploy.
I use the cloud a lot these days, so it was nice to be able to exclude connection information from my code. By doing this, you can use the exact same code in the test environment and production environment, and I think it is important because it reduces the risk of publishing the code on GitHub etc.
Recommended Posts