在进行项目创建之前,先要确保本地有以下软件:
1、MySQL以及Navicat,作者这里用的是MySQL5.7
2、 IDEA
3、MySQL的驱动,作者这里用的是mysql-connector-java-8.0.17.jar
4、Tomcat
1、新建项目
勾选Java EE的Web Application和Create web.xml,继续next
给项目命名并选择存储路径,然后Finish
到这一步项目新建成功
2、进行项目配置
1)点击File->Project Structure
(2)左侧选择Project,右侧配置好SDK,然后点击OK
(3)在WEB-INF下新建两个文件夹,分别是classe和lib,并把mysql-connector-java-8.0.17.jar放入lib文件夹下
(4)点击File->Project Structure->Modules,点击右侧的Paths,选择Use module compile output push,将Output path和Test out path都改成刚才建立的classes的路径,改好后点击Apply。
(5)点击File->Project Structure->Modules,点击右侧的Dependencies,之后点击右侧的+号,选择JARS or directories,然后找到Jar包并选择,点击Apply
然后再选择+号,选择Library,弹框选择Tomcat,点击Add Selected。返回上一页面,点击OK
(6)配置tomcat
点击Run -> 选择Edit Configurations
点击+号 -> 选择Tomcat Server -> 选择Local
在Name处输入新的服务名,点击Application server后面的Configure…,弹出Tomcat Server窗口,选择本地安装的Tomcat目录,选择HTTP port和JMX port(默认值即可),然后点击右下角的Fix,
击Fix后出现如下界面,对下面的Application context进行编辑,编辑好之后点击OK
3、把代码写进jsp文件运行
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %><%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/9/24
Time: 9:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
-%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>mysql测试</title>
</head>
<body>
-%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>mysql测试</title>
</head>
<body>
<%
try {
Class.forName("com.mysql.jdbc.Driver"); ////加载数据库驱动
String url = "jdbc:MySQL://localhost:3306/sqltest?&useSSL=false&serverTimezone=UTC"; //指向数据库table
String username = "root"; //数据库用户名
String password = "123456zyx"; //数据库用户密码
Connection conn = DriverManager.getConnection(url, username, password);
if(conn != null){
out.print("数据库连接成功!");
out.println("<br />");
out.println("-------------------------------");
out.print("<br />");
Statement stmt = null;
ResultSet rs = null;
String sql ="select * from sqltest"; //查询语句
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
out.println("执行结果如下所示:");
out.println("<br />");
out.println("-------------------------------");
out.println("<br />");
out.println("姓名" + "\t" + "电话"+"\t"+"职位"+"\t");
out.println("<br />");
while (rs.next()) {
out.println(rs.getString("name")+"   "+rs.getString("Tel")+"   "+rs.getString("position")+"   "); //将数据库表格查询结果输出
out.print("<br />");
}
}
else{
out.print("连接失败!");
}
}
catch (Exception e) {
out.print("数据库连接异常!");
}
%>
</body>
</html>
运行结果如图所示: