默认机器上已安装并配置好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>