JavaWeb入门-使用JSP和Web.xml连接数据库展示

前言

本人初学JavaWeb,在此简单做下笔记,方便查阅。如有错误,欢迎大家指出!

jsp 从web.xml读取连接数据库的参数,然后显示在界面上

使用application对象提供的方法获取Web项目的全局配置文件信息。

配置文件web.xml配置信息示例如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0">
  <!--配置第一个参数driver-->
  <context-param>
    <param-name>driver</param-name>
    <param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>
  <!--配置第一个参数url-->
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/inspurwebdemo04</param-value>
  </context-param>
  <!--    配置第一个参数user数据库用户名-->
  <context-param>
    <param-name>user</param-name>
    <param-value>root</param-value>
  </context-param>
  <!--    配置第一个参数pass数据库密码-->
  <context-param>
    <param-name>pass</param-name>
    <param-value>123456</param-value>
  </context-param>
</web-app>

因为第7-10行的存在所以要到mysql的jar包,比如:mysql-connector-java-xxx.jar

12-15行,最后那个inspurwebdemo04为数据库的名称

17-20行,数据库登录名

22-25行,数据库登录密码

MySQL数据库表

JSP代码

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %><%--
Created by IntelliJ IDEA.
User: 15131900589
Date: 2022/9/28
Time: 14:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>application对象方法获取Web配置信息</title>
</head>
<body>
<%
//从配置参数中获取驱动
String driver = application.getInitParameter("driver");
//从配置参数中获取数据库URL
String url = application.getInitParameter("url");
//从配置参数中获取用户名
String user = application.getInitParameter("user");
//从配置参数中获取密码
String pass = application.getInitParameter("pass");
//注册驱动
Class.forName(driver);
//获取数据库连接
Connection conn = DriverManager.getConnection(url,user,pass);
//创建Statement对象
Statement stmt = conn.createStatement();
//执行查询
ResultSet rs = stmt.executeQuery("Select * from student");
%>
<h2>查询学生信息</h2>
<table bgcolor="#99CCFF" border="1" >
<tr>
<th>姓名</th>
<th>年龄</th>
<th>家庭住址</th>
</tr>
<%
//遍历结果集
while (rs.next()) {
  %>
  <tr>
  <td><%=rs.getString(1)%></td>
  <td><%=rs.getInt(2)%></td>
  <td><%=rs.getString(3)%></td>
  </tr>
  <%
}
%>
</table>
</body>
</html>

本文来自浪潮优派课本例题。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值