获得Web应用配置参数(连接数据库)

16 篇文章 0 订阅
appclication其中的一个重要用处:可用于获得web应用的配置参数。
如访问数据库,但访问数据库所使用的驱动,URL,用户名及密码都在web.xml中给出.
通过使用application的getInitParameter(String paramName)来获取web应用的配置参数,这些配置参数应该在web.xml中使用context-param元素配置,每个<context-param/>元素配置一个参数,该元素有如下两个子元素.
param-name:配置Web参数名
param-value:配置web参数值.
web.xml文件使用<context-param../>元素配置的参数对整个web应用有效,所以被称为web应用的配置参数.与整个web用用有关的数据,应该通过application对象来操作.

案例:通过配置文件连接数据库
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String driver = application.getInitParameter("driver");
		String url = application.getInitParameter("url");
		String user = application.getInitParameter("user");
		String pass = application.getInitParameter("pass");
		Class.forName(driver);
		Connection connection = DriverManager.getConnection(url, user, pass);
		Statement statement = connection.createStatement();
		ResultSet rSet = statement.executeQuery("select *from student");
		while (rSet.next()) {
			System.out.println(rSet.getString(1));
			System.out.println(rSet.getString(2));
		}
	%>
</body>
</html>

web.xml配置文件信息(建工程的时候勾选自动生成):
如下:


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>2018-3-15</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
  <param-name>driver</param-name>
  <param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>
  <context-param>
  <param-name>url</param-name>
  <param-value>jdbc:mysql://localhost:3306/test</param-value>
  </context-param>
  <context-param>
  <param-name>user</param-name>
  <param-value>root</param-value>
  </context-param>
  <context-param>
  <param-name>pass</param-name>
  <param-value>123456</param-value>
  </context-param>
</web-app>
控制台输出test的所有数据信息:

 
通过这种方式,可以将一些配置信息放在web.xml文件中配置,避免使用硬编码方式写在代码中,从而更好地提高程序的移植性.


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值