Чтобы обмениваться данными между вашим веб-сервисом и клиентом, вы должны выбрать протокол / стратегию, которая наилучшим образом соответствует вашим потребностям (XML, JSON ...).
Поскольку вы используете JavaScript, я рекомендуючтение о JSON (расшифровывается как «JavaScript Object Notation»).
В вашем примере вы должны сгенерировать и вернуть строку JSON (с правильными заголовками типа контента) - вы можете прочитать о пакете javax.json
.С помощью JSON вы можете вернуть структуру данных с выбранными вами полями.
Что-то в этом роде (не проверено - я давно программировал Java):
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
int customerId = Integer.valueOf(request.getParameter("customerId"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
ps.setInt(1, customerId);
ResultSet result=ps.executeQuery();
if(result.next()){
/* set response content type header: jQuery parses automatically response into a javascript object */
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
/* construct your json */
JsonObject jsonResponse = new JsonObject();
jsonResponse.put("firstname", result.getString("firstname"));
jsonResponse.put("telephone", result.getString("telephone"));
/* send to the client the JSON string */
response.getWriter().write(jsonResponse.toString());
// "{"firstname":"first name from db","telephone":"telephone from db"}"
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
В вашемJS (я полагаю, вы используете jQuery из-за обратного вызова success
):
success: function (data) {
/* because you set the content-type header as 'application/json', you'll receive an already parsed javascript object - don't need to use JSON.parse. */
console.log(data);
/*
{
firstname: "first name from db",
telephone: "telephone from db"
}
*/
alert(data.firstname); //alert firstname
alert(data.telephone); //alert phone
}