sp中9个内置对象之一application,它的数据对整个web应用都有效,application有一个重要的用途就是获取web.xm中的配置参数,这样可以提高代码的移植性。应用案例如下:
在web.xml中配置如下代码:
然后在需要使用参数的页面通过getInitParameter()来获取:
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <%@ page import="java.sql.*" %>
- <!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>
- <table border="1">
- <tr><th>编号<th>用户名</th><th>密码</th></tr>
- <%
- String driver = application.getInitParameter("driver");
- 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 stmt = conn.createStatement();
- String sql = "select * from user";
- ResultSet rs = stmt.executeQuery(sql);
- while(rs.next()){
- %>
- <tr><td><%=rs.getString(1)%></td><td><%=rs.getString(2)%></td><td><%=rs.getString(3)%></td></tr>
- <%
- }
- %>
- </table>
- </body>
- </html>
重启tomcat后,参数才起效,可以看到结果: