Preencher campo select (DropDown) com Json usando servlet

Category : Desenvolvimento, Java

Essa semana em um trabalho de servlet da faculdade, precisei preencher um campo select do html dinamicamente, retornando os dados do banco de dados.
A solução que eu fiz, foi criar um servlet que retorne os dados no formato Json e depois preenchi o campo select usando um código em jquery, mas poderia ser apenas o ajax.

1. Criar um arquivo servlet.

2. No método “doGet” do servlet, coloque o código

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PrintWriter out = response.getWriter();
	Statement curStmt;
	Connection con = null;
	try {
		StringBuilder ret = new StringBuilder();
 
		Class.forName("org.postgresql.Driver");
		con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/FaculdadeN50", "postgres", "123456");
		curStmt = con.createStatement();
		ResultSet rs = curStmt.executeQuery("select ID, Nome from Pessoa order by Nome");
 
		while (rs.next() == true) {
			ret.append("{ \"ID\" : \"" + rs.getInt("ID") + "\", \"Valor\" : \"" + rs.getString("Nome") + "\"},");
		}
 
		out.print("[" + ret.toString().substring(0, ret.length() - 1) + "]");	
	} catch (SQLException e) {}
	catch (ClassNotFoundException e) {
	} finally {
		try {
			con.close();
		} catch (SQLException e) {}
	}
}

3. Na página onde for usar, coloque o campo select (DropDown):

1
<select id="IdDoCampoSelect" name="id_select"></select>

4. E o código javascript(obs: para esse exemplo precisa usar o framework Jquery).

View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
$.ajax({
	type: "get",
	url: "nomedoservlet", //coloque o nome do servlet
	data: null,
	dataType: "json",
	async: false,
	success: function(data) {
		$.each(data, function(i, item){
			$("#IdDoCampoSelect").append('<option value="' + item.ID + '">'+ item.Valor +'</option>');
		});
	}
})

Projeto de exemplo no Google Code.