SSM+JQuery+Ajax登录验证

前后端ajax交互验证

使用SSM框架,上次写了SSM的搭建,有兴趣的可以看看 http://blog.csdn.net/qq_36476972/article/details/70212990

好了,接下来直接上代码,实体类 User就直接跳过了 都是getter、setter。 下面是接口方法:

    //验证用户名密码
    @Select("select * from t_user where login_name=#{login_name,jdbcType=VARCHAR} and login_password=#{login_password,jdbcType=VARCHAR}")
    User getByNameAndPwd(@Param("login_name")String login_name,@Param("login_password")String login_password);

然后UserService

package com.ys.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ys.bean.User;
import com.ys.dao.UserDao;

@Service
public class UserService{

    @Autowired
    private UserDao userdao;
    /**
     * 验证登录
     * @param login_name
     * @param login_password
     * @param request
     * @return
     */
    public Map<String, Object> loginValid(String login_name,String login_password,HttpServletRequest request){
        User user=userdao.getByNameAndPwd(login_name, login_password);
        Map<String, Object> map=new HashMap<>();
        if(user==null){
            map.put("status", "userNameOrPwdError");
        }else if(user!=null&&!"".equals(user.getUser_id())){
            map.put("status", "ok");
            map.put("user", user);
            request.getSession().setAttribute("user", user);
        }
        return map;
    }
}

注解不要忘了加上, 下边UseController


@Controller
public class UserController {

    @Autowired
    private UserService userservice;

    //登录
    @RequestMapping(value="login",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> login(String login_name,String login_password,HttpServletRequest request){
        return userservice.loginValid(login_name, login_password, request);
    }

    //注销
    @RequestMapping(value="loginOutput")
    public String loginOutput(HttpServletRequest request){
        request.getSession().invalidate();
        return "index";
    }

下面是index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>     
<%
    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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="login">
<c:if test="${user!=null}">
    <span>${user.user_name} 你好</span>
    <a href="<%=path%>/loginOutput">注销</a>
</c:if>
<c:if test="${user==null }">
<a href="<%=path%>/loginInput">登录</a>
</c:if>
</div>
</body>
</html>

这里做了个判断 读取session里的值判断就好了 如果登录了session就有值 UserService里已经放进去了

最后login.jsp 页面加上JS文件 JQuery和JQuery-validate

<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="<%=path%>/jquery/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="<%=path%>/jquery/jquery.validate.js"></script>
<body>
<form method="post" id="signupForm">
<div id="loginError"></div>
    用户名:<input type="text" name="login_name" id="name"/><br>
    密码:<input type="password" name="login_password" id="pwd"/><br>
    <button id="b">登录</button>
</form>
</body>
<script type="text/javascript">
    $(function(){
        $("#signupForm").validate({
            onsubmit:true,// 是否在提交是验证
            rules: {
                login_name: {
                    required: true,
                    minlength: 5
                },
                login_password: {
                    required: true,
                    minlength: 5
                }
            },
            messages: {
                login_name: {
                    required: "请输入用户名",
                    minlength: "用户名至少为5位"
                },
                login_password: {
                    required: "请输入密码",
                    minlength: "密码长度最少为5位"
                }
            },
            submitHandler: function() { 
            $.ajax({
                url:"${pageContext.request.contextPath}/login",
                method:"post",
                data:$('#signupForm').serialize(),
                dataType:'json',
                success:function(ret){
                    if(ret.status=='ok'){
                        $("#loginError").html("登录成功!");
                        var href = '${pageContext.request.contextPath}/jsp/index.jsp';
                        window.top.location.href = href;
                    }else if(ret.status=='userNameOrPwdError'){
                        $("#loginError").html("用户名或密码错误!");
                    }
                }
            });
            }
        })
    });
</script>
</html>

到这就结束了,有问题留言。

  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值