一个查询数据库的servlet例子

//SelectStudent.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SelectStudent extends HttpServlet {
private String url;
private String user;
private String password;

public void init() throws ServletException {
String driverName=this.getInitParameter("driverClass");
url = this.getInitParameter("url");
user = this.getInitParameter("user");
password = this.getInitParameter("password");
try {
Class.forName(driverName);
} catch(ClassNotFoundException ce) {
ce.printStackTrace();
System.out.println("加载数据库驱动失败!");
}
}
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out=resp.getWriter();
String name = req.getParameter("name");
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DriverManager.getConnection(url,user,password);
String sql = "select * from studentinfo where StudentName = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
ResultSet rs = pstmt.executeQuery();
ResultSetMetaData rsmt = rs.getMetaData();
int iCount = rsmt.getColumnCount();
out.println("<table border=1px bordercolor=#FF0000>");
out.println("<tr>");
for(int i=1;i<=iCount;i++) {
out.println("<td align=center>");
out.println(rsmt.getColumnLabel(i));
out.println("</td>");
}
out.println("</tr>");
while(rs.next()) {
out.println("<tr>");
for(int i=1;i<=iCount;i++) {
out.println("<td align=center>");
out.println(rs.getString(i));
out.println("</td>");
}
out.println("</tr>");
}
out.println("</table>");
} catch (Exception e){}
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
doGet(req,resp);
}
}

//jsp文件
<%@ 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=ISO-8859-1">
<title>学生信息查询</title>
</head>
<body>
<form action="select" method="POST">
姓名:<input type="text" name="name" />
<input type="submit" value="查询"/>
</form>
</body>
</html>

//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<servlet>
<servlet-name>StudentInfo</servlet-name>
<servlet-class>StudentInfo</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>StudentInfo</servlet-name>
<url-pattern>/student</url-pattern>
</servlet-mapping>


<servlet>
<servlet-name>InsertStudent</servlet-name>
<servlet-class>InsertStudent</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>InsertStudent</servlet-name>
<url-pattern>/insert</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>SelectStudent</servlet-name>
<servlet-class>SelectStudent</servlet-class>

<init-param>
<param-name>driverClass</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>

<init-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</init-param>

<init-param>
<param-name>user</param-name>
<param-value>root</param-value>
</init-param>

<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>SelectStudent</servlet-name>
<url-pattern>/select</url-pattern>
</servlet-mapping>



</web-app>
/* * 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>"); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值