关于上篇book.java中使用类型不一样导致的报错
是在bookdao.java中解决
bookservlet.java
package servlet;
import java.io.IOException;
import beans.Book;
import dao.BookDao;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BookServlet extends HttpServlet
{public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{String id =request.getParameter("id");BookDao dao=new BookDao();ArrayList books=dao.queryBookById( id);request.setAttribute("books", books);ServletContext application =this.getServletContext();RequestDispatcher rd=application.getRequestDispatcher("/showBook.jsp");rd.forward(request, response); }
}
新建表books
bookdao.java
package dao;
import java.io.IOException;
import beans.Book;
import java.sql.*;
import java.util.ArrayList;
public class BookDao {
public ArrayList queryBookById(String id) {Connection conn=null;ArrayList books=new ArrayList();try {try {Class.forName("com.mysql.jdbc.Driver");}
catch (ClassNotFoundException e){e.printStackTrace();}String url="jdbc:mysql://localhost:3306/book?useUnicode=true&charaterEncoding=UTF-8";conn=DriverManager.getConnection(url,"root","123456");String sql="select * from books where id=?";PreparedStatement ps=conn.prepareStatement(sql);ps.setString(1, id);ResultSet rs=ps.executeQuery();while(rs.next()){Book book=new Book();book.setId(rs.getInt(1));book.setName(rs.getString(2));book.setPrice(rs.getDouble(3));books.add(book);}rs.close();ps.close();}
catch (SQLException e) {e.printStackTrace();}
finally {try{if(conn!=null){conn.close();conn=null;}}
catch(Exception e){}}return books;}
}
同时把class文件删去,重启启动tomcat6.0
成功访问
使用的是tomcat6.0+jdk1.6+mysql8.0+myeclipse10
注意
创建servlet,先建包
继续更改
tomcat6.0重启,测试结果
附上做好的项目下载链接,可直接导入
https://www.123pan.com/s/9QRqVv-WCuY.html