如何获取数据库表数据(oracle 11g)作为Json对象&在Android中显示该Json对象?

时间:2015-06-24 14:46:46

标签: java android json oracle servlets

我正在尝试在android app和oracle DB之间建立连接。我发现我必须创建一个Web服务,所以我开始编写一个servlet来创建与数据库的连接并将数据作为JSON对象返回,可以在android上解析。 首先,我编写了一个servlet,以HTML格式返回数据非常简单,以下是我的servlet代码

package a.b.c;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDatabaseConnect extends HttpServlet  
{
    protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
    {
        PrintWriter pw=res.getWriter();
        res.setContentType("text/html");        
        String tb=req.getParameter("table");    

        try
        {
             Class.forName("oracle.jdbc.driver.OracleDriver");
             Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
             Statement st=con.createStatement();
             System.out.println("connection established successfully...!!");     

             ResultSet rs=st.executeQuery("Select * from "+tb);

             pw.println("<table border=1>");
                 while(rs.next())
                 {
                     pw.println("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td>"+
                                      "<td>"+rs.getString(3)+"</td></tr>");
                 }
             pw.println("</table>");
             pw.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }
}

如何修改servlet代码以返回JSON对象格式的数据?

2 个答案:

答案 0 :(得分:0)

您必须使用Jackson以json格式转换您的信息,此操作称为序列化,而Jackson是执行此任务的完美工具,您可以看到一些示例here

答案 1 :(得分:0)

在这里,我找到了自己的答案,我使用了JSON-simple-1.1.jar,它可以在java2s.com上免费获得

following is my servlet code now

package servlet.package1;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;




@WebServlet("/ServletTalk")
public class ServletTalk extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public ServletTalk() {
        super();
        // TODO Auto-generated constructor stub


    }

 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //response.setContentType("text/html;charset=UTF-8");
        JSONObject json = new JSONObject();


        //ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
        Enumeration paramNames = request.getParameterNames();

        String[] params = new String[2];
        int i = 0;
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();


            //System.out.println(paramName);
            String[] paramValues = request.getParameterValues(paramName);
            params[i] = paramValues[0];

            //System.out.println(params[i]);
            i++;

        }

        String sql = "SELECT LOGIN_ID, PASSWORD FROM SE_USER where LOGIN_ID=? and PASSWORD=?";
        Connection con = getConnection();

        try {
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, params[0]);
            ps.setString(2, params[1]);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                json.put("info", "success");
                /*String sql1 = "SELECT uname, password FROM users";
                PreparedStatement ps2=con.prepareStatement(sql1);
                ResultSet rs2=ps2.executeQuery();
                JSONArray arrayJSON=new JSONArray();
                while(rs2.next())
                {
                    JSONObject arrayObject = new JSONObject();
                    arrayObject.put("userName", rs2.getString("uname"));
                    arrayObject.put("passWord", rs2.getString("password"));
                    arrayJSON.add(arrayObject);
                }


                json.put("IDS",arrayJSON);*/
            } else {
                json.put("info", "fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //System.out.println(json);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        //json.put("info", disp);
        response.getWriter().write(json.toString());
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    public static Connection getConnection() {
    Connection con = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");//Mysql Connection
        //Class.forName("oracle.jdbc.driver.OracleDriver");//Oracle Connection
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ServletTalk.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        con = DriverManager.getConnection("jdbc:mysql://localhost:8889/a9613246_mydata1", "root", "root");//mysql database
        //con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hemabh_demo", "hemabh_demo");//oracle database

    } catch (SQLException ex) {
        Logger.getLogger(ServletTalk.class.getName()).log(Level.SEVERE, null, ex);
    }
    return con;
}



}

返回的JSON格式不正确,但可以轻松解析而无需任何外部库,如Gson等。

找到答案很有意思...谢谢