1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| package com.xiaoguan.test;
import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException; import java.sql.*; import java.util.ArrayList; import java.util.List;
@WebServlet("/query") public class QueryServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String keywords = request.getParameter("keywords"); Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; StringBuilder stringBuilder = new StringBuilder(); try { Class.forName("com.mysql.cj.jdbc.Driver"); conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/xiaoguan","root","68963120g"); String sql="select content from t_ajax where content like ?"; ps=conn.prepareStatement(sql); ps.setString(1,keywords+"%"); rs=ps.executeQuery(); stringBuilder.append("["); while (rs.next()){ String content = rs.getString("content"); stringBuilder.append("{\"content\":\""+content+"\"},"); }
} catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps!=null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(stringBuilder.substring(0,stringBuilder.length()-1)+"]");
} }
|