JSP结合Servlet动态查询数据库

使用JSP结合servlet动态查询数据库,并展示!

项目示意图:

项目示意图
使用Properties配置文件进行读入读出,可以做到不妨碍程序运行修改数据库配置数据。

即在src源文件夹下创建*.properties后缀文件,也可以创建与src平级的resources文件 文件类型 source Folder,把properties配置文件放入其中:
在这里插入图片描述
此次演示使用的是MySQL数据库,故DBInfo.properties内存放的数据如下

drive=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaTest?useSSL=false&serverTimezone=UTC
user=root
password=tiger

url中?前的javaTest是此次演示的数据库名称,读者需要配置成自己的数据库

编写数据库连接工具类

此工具类具有读取properties配置文件的功能

package com.db.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBConn {
   
	private static String DRIVE;
	private static String URL;
	private static String USER;
	private static String PWD;
	//由于读取配置文件和获取驱动class类只需要一次,故放入静态代码块中
	//在程序加载时就自动编译一次永久使用。
	static{
   
	//读取配置文件
		Properties properties=new Properties();
		InputStreamin=Thread.currentThread().getContextClassLoader().getResourceAsStream("DBInfo.properties");
		try {
   
			properties.load(in);
			//将读取到的配置文件内的数据赋值给类
			DRIVE=properties.getProperty("drive");
			URL=properties.getProperty("url");
			USER=properties.getProperty("user");
			PWD=properties.getProperty("password");
			//获取驱动的class类对象
			Class.forName(DRIVE);
		} catch (IOException e) {
   
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
   
			e.printStackTrace();
		}
	}
	//获取数据库连接的方法
	public static Connection getConnection(){
   
		Connection conn=null;
		
		try {
   
			conn=DriverManager.getConnection(URL,USER,PWD);
		} catch (SQLException e) {
   
			e.printStackTrace();
		}
		return conn;
	}
	//关闭数据库连接的方法
	public static void closeDB(Connection connection,Statement statement,ResultSet resultSet){
   
		try {
   
			if(resultSet!=null){
   
				resultSet.close();
			}
			if(statement!=null){
   
				statement.close();
			}
			if(connection!=null){
   
				connection.close();
			}
		} catch (SQLException e) {
   
			e.printStackTrace();
		}finally{
   
			connection=null;
			statement=null;
			resultSet=null;
		}
	}
}

所用到的数据库相关数据:

t_class数据库
class
t_student数据库
student
表内容请自定

与t_class表对应的T_class类

package com.db.utils;

public class T_class {
   
	private int cno;
	private String cname;
	private String caddr;
	public int getCno() {
   
		return cno;
	}
	public void setCno(int cno) {
   
		this.cno = cno;
	}
	public String getCname() {
   
		return cname;
	}
	public void setCname(String cname) {
   
		this.cname = cname;
	}
	public String getCaddr() {
   
		return caddr;
	}
	public void setCaddr(String caddr) {
   
		this.caddr = caddr;
	}
	public T_class(int cno, String cname, String caddr) {
   
		super();
		this.cno = cno;
		this.cname = cname;
		this.caddr = caddr;
	}
	public T_class() {
   
		super();
	}
	@Override
	public String toString() {
   
		return "T_class [cno=" + cno + 
/* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book (recommended), * visit http://www.davidflanagan.com/javaexamples2. */ package com.hexiang.examples.servlet; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.io.*; /** * This class demonstrates how JDBC can be used within a servlet. It uses * initialization parameters (which come from the web.xml configuration file) * to create a single JDBC database connection, which is shared by all clients * of the servlet. ***/ public class Query extends HttpServlet { private static final long serialVersionUID = -5616899811848789885L; Connection db; // This is the shared JDBC database connection public void init() throws ServletException { // Read initialization parameters from the web.xml file ServletConfig config = getServletConfig(); String driverClassName = config.getInitParameter("driverClassName"); String url = config.getInitParameter("url"); String username = config.getInitParameter("username"); String password = config.getInitParameter("password"); // Use those init params to establish a connection to the database // If anything goes wrong, log it, wrap the exception and re-throw it try { Class.forName(driverClassName); db = DriverManager.getConnection(url, username, password); } catch (Exception e) { log("Can't create DB connection", e); throw new ServletException("Query: can't initialize: " + e.getMessage(), e); } } /** Close the database connection when the servlet is unloaded */ public void destroy() { try { db.close(); } // Try to close the connection catch (SQLException e) {} // Ignore errors; at least we tried! } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); // We're outputting HTML PrintWriter out = response.getWriter(); // Where to output it to // Output document header and a form for entering SQL queries // When the form is submitted, this servlet is reloaded out.println("<head><title>DB Query</title></head>\n" + "<body bgcolor=white><h1>DB Query</h1>\n" + "<form><b>Query: </b><input name='q'>" + "<input type=submit></form>"); // See if a query was specified in this request. String query = request.getParameter("q"); if (query != null) { // display the query text as a page heading out.println("<h1>" + query + "</h1>"); // Now try to execute the query and display the results in a table Statement statement = null; // An object to execute the query try { // Create a statement to use statement = db.createStatement(); // Use it to execute the specified query, and get result set ResultSet results = statement.executeQuery(query); // Ask for extra information about the results ResultSetMetaData metadata = results.getMetaData(); // How many columns are there in the results? int numcols = metadata.getColumnCount(); // Begin a table, and output a header row of column names out.println("<table border=2><tr>"); for(int i = 0; i < numcols; i++) out.print("<th>" + metadata.getColumnLabel(i+1) + "</th>"); out.println("</tr>"); // Now loop through the "rows" of the result set while(results.next()) { // For each row, display the the values for each column out.print("<tr>"); for(int i = 0; i < numcols; i++) out.print("<td>" + results.getObject(i+1) + "</td>"); out.println("</tr>"); } out.println("</table>"); // end the table } catch (SQLException e) { // If anything goes wrong (usually a SQL error) display the // error to the user so they can correct it. out.println("SQL Error: " + e.getMessage()); } finally { // Whatever happens, always close the Statement object try { statement.close(); } catch(Exception e) {} } } // Now, display the number of hits on this page by invoking the // Counter servlet and including its output in this page. // This is done with a RequestDispatcher object. RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet/counter"); if (dispatcher != null) { out.println("<br>Page hits:"); // Add a request attribute that tells the servlet what to count. // Use the attribute name defined by the Counter servlet, and // use the name of this class as a unique counter name. request.setAttribute(Counter.ATTRIBUTE_NAME,Query.class.getName()); // Tell the dispatcher to invoke its servlet and include the output dispatcher.include(request, response); } // Finally, end the HTML output out.println("</body>"); } }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值