java web的后缀名是jsp,所以咱们要有一个jsp的开发环境,我这用的是jspStudy
自行百度。这软件是一个集成开发环境,安装启动后即可使用,集成了tomcat和mysql数据库
首先我们先新建一个首页文件
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>mysql测试</title></head>
<body><%//此进行连接数据库String url="jdbc:mysql://127.0.0.1:3306/test"; //test为数据库名称String dbuser="root"; //数据库账户String dbpwd="root"; //数据库密码try {Class.forName("com.mysql.jdbc.Driver"); //加载驱动 JspStudy} catch (ClassNotFoundException e) { e.printStackTrace();} //取得数据库连接connConnection conn=DriverManager.getConnection(url, dbuser, dbpwd);;PreparedStatement ps=null;ResultSet rs=null;//声明数据库字段String id="";String title="";String img="";try { String sql="select * from res";ps = conn.prepareStatement(sql);rs = ps.executeQuery();while(rs.next()){id=rs.getString(1);title=rs.getString(2);img=rs.getString(3);out.println("ID:"+id+"<br>");out.println(title+"<br><br>"); out.println("<img src=\""+img+"\"/>"+"<br><br>"); }}catch (SQLException e) {e.printStackTrace();}finally{ try {if(rs!=null) rs.close();} catch (SQLException e) {e.printStackTrace();}finally{try {if(ps!=null) ps.close();} catch (SQLException e) { e.printStackTrace();}finally{try {if(conn!=null) conn.close();} catch (SQLException e) { e.printStackTrace();}}}} %>
</body>
</html>
然后拷贝到jspStudy的WWW目录
在浏览器输入http://localhost/index.jsp
即可运行。
当然数据库的数据要有
这是我这边数据库的结构
最终效果: