SpringMVC非常适合跟页面的异步交互。
控制器代码:
package com.smile.controller;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smile.po.UserInfo;
@Controller
public class UserController {
@RequestMapping("/ajaxUser.do")
public void userNumber(String userNumber, HttpServletResponse response) {
System.out.println(userNumber);
try {
// 响应
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
if ("smile".equals(userNumber)) {
out.println("对不起,请重新输入账号");
} else {
out.println("恭喜您,账号可以使用");
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping("/ajaxUser2.do")
public @ResponseBody UserInfo ajaxUser(Integer userId){
System.out.println("编号:"+userId);
UserInfo user = new UserInfo();
user.setUserId(userId);
user.setUserName("张三");
user.setUserAge(18);
return user;
}
}
bean类代码:
package com.smile.po;
/**
* 实体类
*
*/
public class UserInfo {
private Integer userId;
private String userName;
private Integer userAge;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
@Override
public String toString() {
return "UserInfo [userId=" + userId + ", userName=" + userName
+ ", userAge=" + userAge + "]";
}
}
最后来实现jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$().ready(function(){
$("#but01").click(function(){
var userNumber = $("#userNumber").val();
if(userNumber.length == 0){
alert('请输入账号');
}else{
$.post("<%=basePath%>ajaxUser.do",{userNumber:userNumber},function(data){
alert(data);
});
}
});
$("#but02").click(function(){
var userId = $("#userId").val();
$.post("<%=basePath%>ajaxUser2.do",{userId:userId},function(data){
alert(data.userId+' --'+data.userName+' --- '+data.userAge);
},"json");
});
});
</script>
</head>
<body>
<hr>
账号:<input type="text" id="userNumber" name="userNumber"/>
<input type="button" id="but01" value="验证"/>
<hr/>
编号:<input type="text" id="userId" name="userId"/>
<input type="button" id="but02" value="查询"/>
<hr/>
</body>
</html>