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.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; publicclass ImgServlet extends HttpServlet ...{ /** *//** * Constructor of the object. */ public ImgServlet() ...{ super(); } static...{ try...{ Class.forName("com.mysql.jdbc.Driver");//加载驱动 }catch (ClassNotFoundException e) ...{ e.printStackTrace(); } } private Connection getCon()...{ try...{ return DriverManager.getConnection("jdbc:mysql://localhost/test","root","njsan"); }catch (SQLException e) ...{ e.printStackTrace(); returnnull; } } privateint getRecordCount(String sql)...{ int count=0; Connection conn=getCon(); PreparedStatement pstmt=null; try...{ pstmt=conn.prepareStatement(sql); ResultSet rs=pstmt.executeQuery(); if(rs.next())...{ rs.last(); count=rs.getInt("photo_category_id"); } }catch (SQLException e) ...{ e.printStackTrace(); } return count; } private String getImgUrl(int photo_category_id)...{ String imgUrl=""; int recourdCount=getRecordCount("select * from photo"); Connection conn=getCon(); PreparedStatement pstmt=null; ResultSet rs=null; try...{ pstmt=conn.prepareStatement("select * from photo where photo_category_id=?"); if(photo_category_id%recourdCount==0)...{ pstmt.setInt(1,recourdCount); }else...{ pstmt.setInt(1,photo_category_id%recourdCount); } rs=pstmt.executeQuery(); if(rs.next())...{ imgUrl=rs.getString("photo_path"); } }catch (SQLException e) ...{ e.printStackTrace(); }finally...{ try...{ rs.close(); pstmt.close(); conn.close(); }catch (SQLException e) ...{ e.printStackTrace(); } return imgUrl; } } /** *//** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ publicvoid doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{ doPost(request,response); } /** *//** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{ int photo_category_id=Integer.parseInt(request.getParameter("photo_id"));//获取参数 String imgUrl=getImgUrl(photo_category_id); System.out.println(imgUrl); response.getWriter().write(imgUrl); } }