我正在尝试从数据库中检索数据并在中显示出来 jSON
格式。但它正在显示空白页。
下面是我的java代码 JsonServlet.java
文件:
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 javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
/**
* Servlet implementation class JsonServlet
*/
@WebServlet("/JsonServlet")
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JsonServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
response.setContentType("text/html;charset=UTF-8");
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/register","root","toor");
PreparedStatement pstmt = con.prepareStatement(
"select * from headwy " );
ResultSet rs = pstmt.executeQuery();
while(rs.next())
{
out.println("hiii");
JSONObject json = new JSONObject();
json.put("phone", rs.getString(1));
json.put("uname", rs.getString(2));
json.put("pass", rs.getString(3));
out.print(json);
}
}
catch (Exception e2) {System.out.println(e2);
}
}
}
我正在使用 MySQl
作为数据库。下面是使用select查询从数据库表中得到的数据结果:
select * from head;
+----+-------+--------+-------------+
| id | name | salary | designation |
+----+-------+--------+-------------+
| 1 | srinu | 50000 | test |
| 2 | srinu | 500000 | devel |
| 3 | pawan | 100000 | net |
| 4 | ravi | 2000 | .net |
| 5 | ramya | 22222 | tester |
| 6 | srinu | 0 | sql |
| 7 | srinu | 200000 | test |
| 8 | srinu | 1000 | java |
| 9 | srinu | 11111 | html |
| 10 | srinu | 11111 | html |
| 11 | vv | 29999 | hg |
| 12 | s | 147 | aa |
| 13 | srinu | 5000 | test |
+----+-------+--------+-------------+
我需要帮助以正确的方式显示数据 JSON
格式。欢迎提出任何建议。
2条答案
按热度按时间krcsximq1#
你可以这样做:
headobject类
byqmnocz2#
使用像gson这样的库https://github.com/google/gson 使json转换更容易。