注意:<a href="QueryAll">查看</a> 超链接访问servlet默认是doget,只能用doget()
index.jsp
<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<!DOCTYPE html>
<html>
<head>
<%@page import="com.baozi.*,java.sql.*" %>
<a href="QueryAll">查看所有图书信息</a>
</body>
</html>
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);
List<Book>booklist=new ArrayList<Book>();
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);
}
}
网友评论