Utwórz ponownie używaną klasę Javabean reprezentującą jeden wiersz, jedną całość.
public class Category {
private Long id;
private String name;
private String department;
// Add/generate getters/setters/c'tors/equals/hashcode and other boilerplate.
}
Tworzenie reuseable klasy DAO, która odwzorowuje ResultSet
do zbierania tych JavaBeans zwykle JDBC sposób.
public class CategoryDAO {
private static final String SQL_LIST = "SELECT id, name, department FROM category";
// ...
public List<Category> list() throws SQLException {
List<Category> categories = new ArrayList<Category>();
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_LIST);
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
Category category = new Category();
category.setId(resultSet.getLong("id"));
category.setName(resultSet.getString("name"));
category.setDepartment(resultSet.getString("department"));
categories.add(category);
}
}
return categories;
}
// ...
}
Tworzenie klasy serwletu, który wykorzystuje JSON serializatora/Deserializator który pozwala na konwersję między arbirary kolekcji JavaBeans i JSON String, takie jak Google Gson.
@WebServlet("/categories.json")
public class CategoriesJsonServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Category> categories = categoryDAO.list();
String categoriesJson = new Gson().toJson(categories);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(categoriesJson);
} catch (SQLException e) {
throw new ServletException("DB error", e);
}
}
}
Wywołanie go przez http://localhost:8080/contextname/categories.json
. Nie, nie ma zaangażowanego JSP. Nie powinieneś używać JSP dla formatów wyjściowych innych niż HTML.
Wreszcie, w jQuery, wystarczy uzyskać dostęp do zwykłego sposobu $.getJSON()
.
$('#somebutton').click(function() {
$.getJSON('categories.json', function(categoriesJson) {
var $table = $('<table>').appendTo($('#somediv'));
$.each(categoriesJson, function(index, category) {
$('<tr>').appendTo($table)
.append($('<td>').text(category.id))
.append($('<td>').text(category.name))
.append($('<td>').text(category.department));
});
});
});
Dziękuję bardzo czysty i uporządkowany kod – skystar7
@BalusC świetne rozwiązanie, stackoverflow nie byłoby bez ciebie! :) –