默認機器上已安裝並配置好Tomcat服務器,已安裝好MySQL數據庫,JSP的運行環境爲myeclipse,在myeclipse下建立一個web項目test。在test中輸入以下代碼,然後在瀏覽器中打開localhost:8080/你的項目名/test,運行之後會出現以下結果,就代表服務器連接成功。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
try{
Class.forName("com.mysql.jdbc.Driver");//記載數據庫驅動,註冊到驅動管理器
String url="jdbc:mysql://localhost:3306/test"; //根據自己的情況修改mysql數據庫id和端口,test是數據庫上存在的一個庫
String username="root"; //登錄賬號
String password="root"; //登錄密碼
Connection conn=DriverManager.getConnection(url,username,password);
if(conn!=null){
out.println("mysql數據庫連接成功!!!");
}else{
out.println("數據庫連接失敗!!!");
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}
%>
</body>
</html>