1. package com.wjh.controller;
    2. import com.fasterxml.jackson.databind.ObjectMapper;
    3. import com.wjh.po.Incident;
    4. import com.wjh.util.JdbcUtils;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import java.io.IOException;
    11. import java.io.PrintWriter;
    12. import java.sql.Connection;
    13. import java.sql.PreparedStatement;
    14. import java.sql.ResultSet;
    15. import java.sql.SQLException;
    16. @WebServlet("/testServlet")
    17. public class testServlet extends HttpServlet {
    18. @Override
    19. protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    20. Incident incident=new Incident();
    21. Connection con= JdbcUtils.getConnection();//获取数据库连接
    22. String sql="SELECT * FROM incident WHERE incident_id=2";
    23. try {
    24. PreparedStatement ps=con.prepareStatement(sql);
    25. ResultSet rs=ps.executeQuery();
    26. while (rs.next()){
    27. incident.setIncidentTitle(rs.getString("incident_title"));
    28. incident.setIncidentContent(rs.getString("incident_content"));
    29. incident.setPublisher(rs.getString("publisher"));
    30. }
    31. } catch (SQLException e) {
    32. e.printStackTrace();
    33. }
    34. String json="";
    35. if(incident!=null){
    36. ObjectMapper objectMapper=new ObjectMapper();
    37. json=objectMapper.writeValueAsString(incident);
    38. }
    39. System.out.println("json字符串:"+json);
    40. PrintWriter pw= response.getWriter();
    41. pw.println(json);
    42. pw.flush();
    43. pw.close();
    44. }
    45. }
    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <title>Title</title>
    5. </head>
    6. <script>
    7. function search(){
    8. let xmlHttp = new XMLHttpRequest();
    9. xmlHttp.onreadystatechange=function (){
    10. if(xmlHttp.readyState === 4 && xmlHttp.status === 200){
    11. let data = xmlHttp.responseText;//接收后台发送的json字符串
    12. window.eval("var incident="+data);//把json字符串转化为json对象
    13. var text="";
    14. text+= "<tr>";
    15. text+="<td>"+incident.incidentTitle+"</td>";
    16. text+="<td>"+incident.incidentContent+"</td>";
    17. text+="<td>"+incident.publisher+"</td>";
    18. text+="</tr>";
    19. document.getElementById("tbody").innerHTML=text;
    20. }
    21. }
    22. xmlHttp.open("get", "testServlet", true);
    23. //4.发起请求
    24. xmlHttp.send();
    25. }
    26. </script>
    27. <body>
    28. <input type="button" value="查询瓜" onclick="search()">
    29. <table border="1px" width="40%">
    30. <tr>
    31. <th>标题</th>
    32. <th>内容</th>
    33. <th>发布者</th>
    34. </tr>
    35. <tbody id="tbody">
    36. </tbody>
    37. </table>
    38. </body>
    39. </html>

    运行结果:
    image.png
    image.png