使用ajax与Gson实现登录验证

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);
            }
        }
    });
}
  1. 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();

到此一个简单的登录验证模块搭建完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值