友。 我想填充搜索框,这个搜索框就像一个下拉列表,当用用户的全名(由名字和姓氏组成)输入内容时,它会动态填充。 jsp表单有这个搜索框(下拉列表)。我正在使用ajax,以便当用户在搜索框中输入名称时,我可以动态显示包含所有用户全名的ArrayList。 我对ajax或jquery完全不熟悉。请指导我从servlet传递arrayList数据作为对ajax或jquery脚本的响应,并异步填充下拉列表。 请帮忙
这是我的servlet代码
@WebServlet("/someservlet/*")
public class AjaxExampleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Database connection
try {
Connection currentCon = ConnectionManager.getConnection();
currentCon.setAutoCommit(true);
ResultSet rs;
Statement stmt = null;
stmt = currentCon.createStatement();
//create the query
String query = "select firstname,lastname,username from users";
//executing the query
rs = stmt.executeQuery(query);
//creating a hashmap
ArrayList<String> UserFullName = new ArrayList<String>();
//fill the hashmap UserFullName with firstname and lastname of the user fetched from the database
while(rs.next())
{
UserFullName.add(rs.getString("firstname") + rs.getString("lastname"));
}
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8");
request.setAttribute("list", UserFullName);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("response.jsp");
requestDispatcher.forward(request, response);
和我的第一个jsp页面
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<form action="someservlet" method="get">
<button type="submit" id="somebutton">press here</button>
</form>
</body>
</html>
和我的response.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv">
<label for="users">Users</label>
<select id="users" multiple="multiple">
<c:forEach var="listvar" items="${list}">
<option value="${listvar}">${listvar}</option>
</c:forEach>
</select>
</div>
</body>
</html>
我希望我的响应在第一个jsp页面的同一个jsp中,其中使用ajax,jquery直接搜索到搜索下拉列表的用户。 欢迎举例。请帮助朋友。