jsp-application應用
阿新 • • 發佈:2017-06-07
sta reat -- color 遍歷 ++ 讀取 itl class
application有兩種應用,1是當作map,代碼如下
1 <body> 2 <%! 3 int i=1; 4 %> 5 <% 6 application.setAttribute("count",String.valueOf(i++)); 7 %> 8 <%=application.getAttribute("count") %> 9 </body>
利用setAttribute和getAttribute。
2是讀取web.xml配置信息,代碼如下:首先web.xml代碼:
1 <!--配置歡迎頁 --> 2<welcome-file-list> 3 <welcome-file>index.jsp</welcome-file> 4 </welcome-file-list> 5 <!-- 驅動 --> 6 <context-param> 7 <param-name>driver</param-name> 8 <param-value>com.mysql.jdbc.Driver</param-value> 9</context-param> 10 <context-param> 11 <!-- url --> 12 <param-name>url</param-name> 13 <param-value>jdbc:mysql://localhost:3306/house</param-value> 14 </context-param> 15 <!-- 連接用戶 --> 16 <context-param> 17<param-name>user</param-name> 18 <param-value>root</param-value> 19 </context-param> 20 <!-- 連接密碼 --> 21 <context-param> 22 <param-name>pwd</param-name> 23 <param-value>123456</param-value> 24 </context-param>
然後jsp代碼:
<[email protected] import="java.sql.ResultSet"%> <[email protected] import="com.mysql.jdbc.Statement"%> <[email protected] import="java.sql.DriverManager"%> <[email protected] import="com.mysql.jdbc.Connection"%> <%@ page language="java" contentType="text/html; charset=gbk" pageEncoding="gbk"%> <!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=gbk"> <title>Insert title here</title> </head> <body> <% String driver = application.getInitParameter("driver"); String url = application.getInitParameter("url"); String user = application.getInitParameter("user"); String pwd = application.getInitParameter("pwd"); //加載驅動 Class.forName(driver); //建立連接 Connection conn = (Connection) DriverManager.getConnection(url, user, pwd); //創建Statement Statement stm = (Statement) conn.createStatement(); //執行查詢 ResultSet rs = stm.executeQuery("select username,pwd from user"); %> <table border="1" width="300"> <% //遍歷結果 while (rs.next()) { %> <tr> <td><%=rs.getString(1)%></td> <td><%=rs.getString(2)%></td> </tr> <% } %> </table> </body> </html>
jsp-application應用