How to generate/send (Server-Side) JSON via Java and receive via Jquery (Client-Side)?

Asked

Viewed 559 times

0

I’m having trouble exchanging information between my web application (client) and my application java on the server side. I am trying to query the server via JQuery and hoping to receive as a return json. On the server side I’m using java to generate the json.

I’m making a request via ajax as follows:

    <script type="text/javascript">
        $("document").ready (function() {
                $.ajax ({
                        crossDomain: true,
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        async: true,
                        url: "https://www.testeservidor.com/FrontController?action=testeJSON",
                        data: {user:"usuarioComum"},
                        dataType: "json",
                        jsonpCallback: 'fnsuccesscallback',
                        success: function (data) {
                            alert (data.user);
                        }
                });
   });

    </script>

And on the server side, my servlet this way:

public class TesteJSON {

    public TesteJSON() {}

    public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
                {
                    JSONObject json = getLoginAndPassword(request.getParameter("user"));
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    writer.write(json.toString());
                    System.out.println("OK");
                }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }

public static JSONObject getLoginAndPassword(String usuario) throws SQLException, ClassNotFoundException, Exception {
        PreparedStatement stmt = null;
        Connection conn = null;
        ResultSet result = null;
        JSONObject userJson = null;

        try {
            conn = Conexao.getInstance().getConnection();
            String sql = "SELECT user_login FROM Usuario WHERE user_login = ?";

            stmt = conn.prepareStatement(sql);
            stmt.setString(1, usuario);
            result = stmt.executeQuery();

            if (!result.next())
                throw new Exception ("Não foi encontrado nenhum registro " + usuario);
            else {
                String login = result.getString(1);
                userJson = new JSONObject();
                userJson.put("user", login);
            }

            return userJson;

        } catch (SQLException e) {
            throw e;
        } finally {
            try {
                if (stmt != null)
                    stmt.close();

                if (conn != null)
                    stmt.close();

            } catch (SQLException e) {
                throw e;
            }
        }

    }

}

Would anyone have any hint of what might be going wrong?

Note: I used as a reference, this link below:

Cross Domain Ajax request to a json

  • What mistake is happening exactly?

  • I’m not getting any return value from my server

  • In the browser’s Dev Tools console some error appears?

  • This message appeared on the Chrome Console: Xmlhttprequest cannot load https://www.testeservor.com/FrontController?action=TesteJSON. No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://www.testecliente.com.br' is therefore not allowed access.

  • 2

    See if you can get help http://stackoverflow.com/questions/20433655/no-access-control-allow-origin-header-is-present-on-the-requested-resource-or

  • Thank you @adelmo00 ! As the link you passed, just add Sponse.addHeader("Access-Control-Allow-Origin", "http://www.example.com"); which worked!

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.