web项目中经常使用ajax实现页面数据交互,同时结合Gson实现json与bean的转换,以下以一个登录模块来熟悉相关技术。
使用maven搭建工程
1.引入Gson
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
2.登录界面,使用表单向服务器发送登录信息
<form id="LoginForm" method="post">
UserName:<input type="text" name="username"/>
<br/>
<div id="message"></div>
<br/>
<input type="button" id='submitBtn' name="Submit" value=' 登 录 ' onclick='userLogin();'/>
<br/>
<div id="error_msg"></div>
<br/>
</form>
3.需要引入jquery.form.js来使用ajax提交form表单,返回数据格式为json
function userLogin() {
var userName = $.trim($("#username").val());
$("#LoginForm").ajaxSubmit({
url: "${pageContext.request.contextPath}/userlogin",
type: "post",
data: $('#LoginForm').formSerialize(),
dataType: 'json',
async: false,
success: function (data) {
if(data.status == 200){
location.href = "${pageContext.request.contextPath}/goods/list";
} else if (data.status == 500) {
$("#username").val('');
$("#error_msg").html(data.status);
}
}
});
}
- ajaxSubmit提交给后台处理,后台我们使用Map存放ajax返回数据,
Map
GsonBuilder gb = new GsonBuilder();
gb.setDateFormat("yyyy-MM-dd");
String json = gb.create().toJson(resultMap);
如果查询到相关记录,推入相关的状态码给resultMap
String queryResult = userService.queryUserName(username);
if (queryResult == null) {
LOG.info("错误的用户名【" + username + "】");
throw new Exception();
} else {
resultMap.put("status", GlobalConstants.STATUS_SUCCESS);
LOG.info("正确的用户名【" + username + "】");
}
response.setContentType("text/html" + ";charset=utf-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().write(json);
response.getWriter().flush();
到此一个简单的登录验证模块搭建完成