2011-07-03 98 views

回答

15

創建一個表示一行,一個實體的可重用Javabean類。

public class Category { 
    private Long id; 
    private String name; 
    private String department; 

    // Add/generate getters/setters/c'tors/equals/hashcode and other boilerplate. 
} 

創建一個可重複使用的DAO類的ResultSet映射到一個集合這些的JavaBeans通常的JDBC方式。

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; 
    } 

    // ... 
} 

創建其使用JSON串行器/解串器,其能夠Java Bean的arbirary收集和JSON字符串之間進行轉換,例如一個Google Gson servlet類。

@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); 
     } 
    } 

} 

通過http://localhost:8080/contextname/categories.json調用它。不,不涉及JSP。您不應該將JSP用於HTML以外的輸出格式。

最後,在jQuery中,只需訪問它通常的$.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)); 
     }); 
    }); 
}); 
+2

非常感謝你乾淨整理好的代碼 – skystar7

+3

@BalusC很棒的解決方案,如果沒有你,stackoverflow將不會一樣! :) –

3

要創建您的json,您可以使用google-gson庫。

然後,處理jQuery中您的JSON,這取決於你的需求,但假設你想顯示在一個表中,你可以做到這一點通過以下方式:

HTML:

<table id="mytable"> 
    <tr> <th> Name </th> <th> Department </th> </tr> 
</table> 

Javascript:

$.getJSON("your_url", function(categories){ 
    for(var i=0; i<categories.length; i++){ 
     var name = categories[i].name; 
     var department = categories[i].department; 
     $("#mytable").append('<tr><td>'+ name +'</td><td>'+department+'</td></tr>'); 
    } 
}); 

希望這會有所幫助。乾杯