package com.wjh.controller;import com.fasterxml.jackson.databind.ObjectMapper;import com.wjh.po.Incident;import com.wjh.util.JdbcUtils;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;@WebServlet("/testServlet")public class testServlet extends HttpServlet {@Overrideprotected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Incident incident=new Incident();Connection con= JdbcUtils.getConnection();//获取数据库连接String sql="SELECT * FROM incident WHERE incident_id=2";try {PreparedStatement ps=con.prepareStatement(sql);ResultSet rs=ps.executeQuery();while (rs.next()){incident.setIncidentTitle(rs.getString("incident_title"));incident.setIncidentContent(rs.getString("incident_content"));incident.setPublisher(rs.getString("publisher"));}} catch (SQLException e) {e.printStackTrace();}String json="";if(incident!=null){ObjectMapper objectMapper=new ObjectMapper();json=objectMapper.writeValueAsString(incident);}System.out.println("json字符串:"+json);PrintWriter pw= response.getWriter();pw.println(json);pw.flush();pw.close();}}
<!DOCTYPE html><html><head><title>Title</title></head><script>function search(){let xmlHttp = new XMLHttpRequest();xmlHttp.onreadystatechange=function (){if(xmlHttp.readyState === 4 && xmlHttp.status === 200){let data = xmlHttp.responseText;//接收后台发送的json字符串window.eval("var incident="+data);//把json字符串转化为json对象var text="";text+= "<tr>";text+="<td>"+incident.incidentTitle+"</td>";text+="<td>"+incident.incidentContent+"</td>";text+="<td>"+incident.publisher+"</td>";text+="</tr>";document.getElementById("tbody").innerHTML=text;}}xmlHttp.open("get", "testServlet", true);//4.发起请求xmlHttp.send();}</script><body><input type="button" value="查询瓜" onclick="search()"><table border="1px" width="40%"><tr><th>标题</th><th>内容</th><th>发布者</th></tr><tbody id="tbody"></tbody></table></body></html>
运行结果:

