Create a reusable Javabean class that represents a single row, a single entity.
public class Category { private Long id; private String name; private String department;
Create a reusable DAO class that maps the ResultSet to the collection of these Javabeans in the usual JDBC way.
public class CategoryDAO { private static final String SQL_LIST = "SELECT id, name, department FROM category";
Create a servlet class that uses the JSON serializer / deserializer that can convert between the arbirary Javabeans collection and the JSON String, such as 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); } } }
Call it http://localhost:8080/contextname/categories.json . No, no JSP. You should not use JSP for output formats other than HTML.
Finally, in jQuery just run it in the usual way $.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)); }); }); });
source share