Servlet jdbc查询

注意:查看 超链接访问servlet默认是doget,只能用doget()
index.jsp

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>



<%@page import="com.baozi.*,java.sql.*" %>
查看所有图书信息


QueryAll

package com.baozi;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="QueryAll",urlPatterns="/QueryAll") 
public class QueryAll extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Dao dao=new Dao();
        Connection conn=dao.getConnection();
        try {
            response.setContentType("text/html");
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            Statement stmt=conn.createStatement();
            String sql="select id,name,price,bookCount,author from tb_books;";
            ResultSet rs=stmt.executeQuery(sql);
            Listbooklist=new ArrayList();
            while(rs.next()) {
                Book book=new Book();
                book.setId(rs.getInt("id"));
                book.setName(rs.getString("name"));
                book.setPrice(rs.getDouble("price"));
                book.setBookCount(rs.getInt("bookCount"));
                book.setAuthor(rs.getString("author"));
                booklist.add(book);
            }
            request.setAttribute("booklist", booklist);
            rs.close();
            stmt.close();
            conn.close();           
        } catch (SQLException e) {
            e.printStackTrace();
        }
        request.getRequestDispatcher("book_list.jsp").forward(request, response);
        System.out.println("跳转完成!");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //doGet(request, response);

    }

}

你可能感兴趣的:(Servlet jdbc查询)