一、JSP代码
1、 函数部分
<script type="text/javascript">
var xmlHttp;
//自定义一个方法,代替document.getElementById()
function $(id) {
return document.getElementById(id);
}
//建立XMLHttpRequest对象
function createXmlHttpRequest() {
alert("createXmlHttpRequest方法已经运行");
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
return new XMLHttpRequest();
}
}
//ajax中Post方法提交数据
function loadUser() {
alert("loadUser方法已经运行");
xmlHttp = createXmlHttpRequest();
xmlHttp.open("post", "InfoServlet", true);
xmlHttp.setRequestHeader("content-type",
"application/x-www-form-urlencoded");
//设置回调函数
xmlHttp.onreadystatechange = userCallBack;
var userName = $("data").value;
var param = "userName=" + encodeURIComponent(userName) + "&act="
+ "loadUser";
xmlHttp.send(param);
}
//回调函数
function userCallBack() {
alert("userCallBack方法已经运行");
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert("状态正常");
//将JSON字符串转成JSON对象,再将JSON对象转成Java对象
//var json=new JSONObject().fromObject(xmlHttp.responseText);
//var user=JSONObject.toBean(json,User.class);
//alert(user.toString());
alert(xmlHttp.responseText);
//服务器端返回字符串类型,转成JSON对象
var user = eval('('+xmlHttp.responseText+')');
//获取数据
var password = user.password;
var email = user.email;
var introduce = user.introduce;
var photo = user.photo;
var tel = user.tel;
$("password").value = password;
$("repassword").value = password;
$("email").value = email;
$("introduce").value = introduce;
$("photo").value = photo;
$("tel").value = tel;
}
}
}
//验证表单
function check(input) {
var content = input.value;//获取输入值
var id = "msg_" + input.id;
var msg = document.getElementById(id);
var regexp = null;
if (content == "") {
msg.innerHTML = "<img src='image/false.gif'/>不能为空";
return false;
} else {
if (input.id == "password") {
regexp = /[a-z][A-Z][0-9]/;
var result = content.match(regexp);
if (content.match(".{6,16}") != content) {
msg.innerHTML = "<img src='image/false.gif'/>密码必须是6到16位";
return false;
} else {
msg.innerHTML = "<img src='image/right.gif'/>";
}
} else if (input.id == "repassword") {
var password = document.getElementById("password");
if (input.value != password.value) {
msg.innerHTML = "<img src='image/false.gif'/>密码确认和密码不一致";
return false;
} else {
msg.innerHTML = "<img src='image/right.gif'/>";
}
} else if (input.id == "tel") {
if (content.match("\\d{11}") != content) {
msg.innerHTML = "<img src='image/false.gif'/>手机号码格式不正确";
return false;
} else {
msg.innerHTML = "<img src='image/right.gif'/>";
}
} else {
msg.innerHTML = "<img src='image/right.gif'/>";
}
}
}
</script>
2、表单
<body onload="loadUser()">
<!-- 通过url来传递数据 -->
<form action="InfoServlet" method="post">
<table>
<tr>
<th>账号</th>
<td>${sessionScope.user }<span style="color: red;"
id="msg_userName"></span>
</td>
</tr>
<tr>
<th>密码</th>
<td><input type="password" name="password" id="password"
onclick="loadUser()" onblur="check(this)"> <span
style="color: red;" id="msg_password"><img
src="image/require.gif" />密码6-16位,必须包含字母数字</span></td>
<tr>
<th>密码确认</th>
<td><input type="repassword" name="repassword"
id="repassword" onblur="check(this)" /> <span style="color: red;"
id="msg_repassword"><img src="image/require.gif" /></span></td>
</tr>
<tr>
<th>邮箱</th>
<td><input type="text" name="email" id="email"
onblur="check(this)" /> <span style="color: red;" id="msg_email"><img
src="image/require.gif" /></span></td>
</tr>
<tr>
<th>个人简介</th>
<td><textarea id="introduce" cols="18" rows="3"
onblur="check(this)"></textarea> <span style="color: red;"
id="msg_introduce"><img src="image/require.gif" /></span></td>
</tr>
<tr>
<th>头像</th>
<td><input type="text" name="photo" id="photo"
onblur="check(this)" /> <span style="color: red;" id="msg_photo"><img
src="image/require.gif" /></span></td>
</tr>
<tr>
<th>联系电话</th>
<td><input type="text" name="tel" id="tel"
onblur="check(this)" onclick="hello()" /> <span
style="color: red;" id="msg_tel"><img
src="image/require.gif" />必须是11位</span></td>
</tr>
</table>
<input type="hidden" id="data" value="${sessionScope.user }" style="display:none"/>
<input type="reset" value="重置" /><input type="submit" value="提交" />
</form>
</body>
二、Servlet部分
public class InfoServlet extends HttpServlet {
User user=new User();
UserBiz userBiz=new UserBiz();
/*请求处理*/
public void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String act=request.getParameter("act");
System.out.println("service方法正在运行");
System.out.println(act);
if("loadUser".equals(act)) {
this.loadUser(request,response);
}
}
/*加载指定员工的信息*/
public void loadUser(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
System.out.println("loadUser()方法正在执行");
//获取从客户端发送的数据
HttpSession session=request.getSession();
//String userName=request.getParameter("userName");
String userName=(String)session.getAttribute("user");
System.out.println(userName);
user=userBiz.getByUserName(userName);
System.out.println(user.toString());
/*调用JSON的库将Java对象转成JSON对象*/
//JSONObject json=JSONObject.fromObject(obj);
/*将JSON对象转成字符串*/
//String str=json.toString
/*将Java对象转成JSON对象,然后转成字符串*/
out.print(JSONObject.fromObject(user));
//在控制台输出结果
System.out.println(JSONObject.fromObject(user));
out.flush();
out.close();
}
}
写完这段代码以后,还得在web.xml中配置Servlet
三、小结
在本次试验中,使用了JSON对象,所以一定要引"Java JSON 包"。本例中通过Ajax请求和接收数据的过程中遇到了很多问题,大多是
语法错误,如下所示:
(1)JSP变量声明方式不当
例如:String password=user.password;
按照JavaScript中声明变量的方法,正确的写法是:var password=user.password.
(2)Ajax中通过param传递多个参数,param出现语法错误
例如:var param="userName="+encodeURIComponent(userName)+"act="+encodeURIComponent("loadUser");
这样的写法是错误的,Ajax中通过param传递多个参数,param的正确写法是:var param="userName"+
encodeURIComponent(userName)+"&act=loaderUser";
(3)混淆了通过JSON传递对象和列表的使用方法
通过JSON对象传递单个对象和列表数据时,发送端和接收端的写法略有不同,如果是列表写法如下:
发送端(Servlet):out.print(JSONArray.fromObject(users));//其中users是List类型的列表,这个方法的作用是将List对象
转成JSON对象。
接收端(JSP):var users=eval(xmlHttp.responseText);//服务器端返回字符串类型,转成JSON对象。其中xmlHttp是XMLHttpRequest对象
但如果是传递单个对象的话,写法如下:
发送端(Servlet):out.print(JSONObject.fromObject(user));//注意是JSONObject类,user是单个对象
接收端(JSP):var user=eval('('+xmlHttp.responseText+')');//注意两个括号不能省