Userservlet.java代碼
package com.iss.servlet;
import org.json.JSONException;
import org.json.JSONObject;
import com.iss.pojo.User;
import com.iss.util.JSONUtil;
public class UserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//list 添加對象
List<User> userList = new ArrayList<User>();
User user1 = new User("張三", "男", "18");
User user2 = new User("李四", "男", "19");
User user3 = new User("王五", "男", "20");
userList.add(user1);
userList.add(user2);
userList.add(user3);
PrintWriter out = response.getWriter();
String str = null;
try {
//帳號密碼如果匹配則把list 返回給界面
if (request.getParameter("userName").equals("jquery")
&& request.getParameter("password").equals("ajax")) {
str = JSONObject.quote(JSONUtil.toJSONString(userList));
}
out.print(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("str "+str);
out.flush();
out.close();
}
}
Html代碼
<body>
帳號jquery 密碼ajax
<form id="mainform">
<ul>
<li>
帳號
<input type="text" name="userName" />
</li>
<li>
密碼
<input type="password" name="password" />
</li>
<li>
<input onclick="login()" type="button" value="登錄" />
</li>
</ul>
</form>
查詢到的數據
<p id="pa">
</p>
<script type="text/javascript">
function login(){
//獲取form的參數
var args =$("#mainform").serialize();
//調用jquery 的json獲取方法
//三個參數分別為 :請求路徑 ,請求參數,返回數據的回調函數
$.getJSON("servlet/UserServlet",args,function (data){
if(data!=null){
// 界面返回的是一個json格式字符串 調用JSON.parse()把數據轉化為json
// 格式的對象
var jsondata =JSON.parse(data);
parseData(jsondata);
}else{
alert("帳號密碼輸入有誤");
}
})
}
function parseData(data){
var str="";
//遍歷json格式數據
for (var key in data){
strstrstr =str+" 用戶"+data[key].userName+" 年齡"+data[key].age+"<br/>"
alert(str);
}
//把數據添加到p中
$("#pa").html(str);
}
</script>
</body>
www.aiwalls.com
UserServlet 記得要導入 工具類JSONStringObject JSONUtil
jsp 要導入 jquery.js和json.js
作者 王德封-逐浪