I'm having trouble exchanging information between my web application (client) and my application java
on the server side. I'm trying to query the server via JQuery
and expecting to get a json
return. On the server side I am using java
to generate json
.
I am 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
looks like this:
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 suggestions for what might be going wrong?
Note: I used this link as a reference below: