java web的后缀名是jsp,所以咱们要有一个jsp的开发环境,我这用的是jspStudy
![](https://img-blog.csdn.net/20180622145147820?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zOTkyNzg1MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
自行百度。这软件是一个集成开发环境,安装启动后即可使用,集成了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");
- }
- catch (ClassNotFoundException e)
- {
- e.printStackTrace();
- }
-
- Connection 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
即可运行。
当然数据库的数据要有
这是我这边数据库的结构
![](https://img-blog.csdn.net/20180622145225592?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl8zOTkyNzg1MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
原文地址https://blog.csdn.net/weixin_39927850/article/details/80773736