Servlet上连接数据库的小案例

本文介绍了一个使用Java Servlet和MySQL数据库进行用户验证的示例。通过建立Servlet文件,实现从数据库中读取用户信息并显示的功能。该示例涵盖了数据库连接、SQL查询执行以及结果集的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个是在配置已经配置好的情况下进行的。

使用的是mysql数据库;

在test数据库下建立一个名为user的表,如果:

访问数据库:

建立一个servlet文件,内容如下:

package com.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.Out;
import java.sql.*;
/**
 * Servlet implementation class LoginValidate
 */
@WebServlet(name="LoginValidate", value="/LoginValidate")
public class LoginValidate extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	// JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/test";
    
    // 数据库的用户名与密码,需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "123456"; 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginValidate() {
        super();
        // TODO Auto-generated constructor stub
    }

    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
    	Connection conn = null;
        Statement stmt = null;
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String title = "Servlet Mysql 测试 - 菜鸟教程";
        String docType = "<!DOCTYPE html>\n";
        out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n" +
        "<body bgcolor=\"#f0f0f0\">\n" +
        "<h1 align=\"center\">" + title + "</h1>\n");
        
        try{
            // 注册 JDBC 驱动器
            Class.forName("com.mysql.jdbc.Driver");
            // 打开一个连接
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
            // 执行 SQL 查询
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT * FROM user";
            ResultSet rs = stmt.executeQuery(sql);
            // 展开结果集数据库
            while(rs.next()){
                // 通过字段检索
                int id  = rs.getInt("userid");
                String name = rs.getString("username");
                String pwd = rs.getString("password");
    
                // 输出数据
                out.println("userID: " + id);
                out.println(",username: " + name);
                out.println(", password: " + pwd);
                out.println("<br />");
            }
            out.println("</body></html>");

            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        } catch(SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch(Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        }finally{
            // 最后是用于关闭资源的块
            try{
                if(stmt!=null)
                stmt.close();
            }catch(SQLException se2){
            }
            try{
                if(conn!=null)
                conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
	}
}

 

/* * 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、付费专栏及课程。

余额充值