查询数据库数据并传入servlet

东哥笔记 2020-02-18

功能:servlet读取前台要查询的值(des),调用查询函数,得到查到的值的列表,再将列表值传到前台显示。

servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        QueryFromMySql queryFromMySql=new QueryFromMySql();  //查询数据库类
        request.setCharacterEncoding("utf-8");  //设置读取编码
        String des=request.getParameter("des");  //通过des查询
        List<CiTiao> ciTiaos=queryFromMySql.SearchByDes(des);
        System.out.println(ciTiaos.get(0).toString());
        int count=queryFromMySql.query();
        System.out.println(count);
        request.setAttribute("citiaos", ciTiaos);   //将查询得到的结果传到前台jsp页面
        request.getRequestDispatcher("/list_sort.jsp").forward(request, response);
    }

QueryFormMySql:

private static String DriverName="com.mysql.jdbc.Driver";
    private static String UName="root";
    private static String Upwd="root";
    private static String Url="jdbc:mysql://192.168.25.1:3306/xinjian?useUnicode=true&characterEncoding=UTF-8";
public List<CiTiao> SearchByDes(String des)  //根据分类查询所有的词条信息
      {
          List<CiTiao> CiTiaos=new ArrayList<CiTiao>();
          CiTiao CiTiao=null;
          Connection conn=null;
          PreparedStatement pstmt=null;
          ResultSet result=null;
          try {
              Class.forName(DriverName);
              conn=DriverManager.getConnection(Url, UName, Upwd);
              String sql="select * from citiao where des like ?";
              pstmt= conn.prepareStatement(sql);
              pstmt.setString(1,"%"+des+"%");
              result=pstmt.executeQuery();
                  while(result.next())
                  {
                       String name=result.getString("name");  //词条名称2
                       des=result.getString("des");  //词条简单内容3
                       String url=result.getString("url");  //词条链接4
                       
                     CiTiao=new CiTiao(name,des,url);
                     CiTiaos.add(CiTiao);
                  }
              return CiTiaos;
          }
          catch(ClassNotFoundException e)
          {
              e.printStackTrace();
              return null;
          } 
          catch (SQLException e) 
          {
            e.printStackTrace();
            return null;
        }
          catch(Exception e)
          {
              e.printStackTrace();
              return null;
          }
          finally {
              try {
                  if(result!=null) result.close();
                  if(pstmt!=null) pstmt.close();
                  if(conn!=null) conn.close();
              }
              catch(SQLException e)
              {
                  e.printStackTrace();
              }
          }
      }

相关推荐