jquery + javaweb achieve a complete source code Login

Realization of ideas: Jquery first front-end verification, and then check before submitting. Jquery Ajax then send asynchronous requests, Servlet receives the request, Service logic processing. Then connect to the database through C3P0 JDBCUtil, the final response to the front end.


Let's look at specific implementation code!

HTML code block

 Front end block

<div class="bigbox">
<div class="box">
<div class="box_form">
<form action=action="${ctx}/LoginServlet"  method="post" role="form" >
                    <div class="form-group user">
                        <div class="input-group">
                            <div class="input-group-addon">
                                <i class="fa fa-user"></i>
                            </div>
                            <input class="form-control" id="username-input" type="text" autocomplete="off" placeholder=" 请输入帐号" name="username">
                        </div>
                        <div id="username-error" class="error"></div>
                    </div>
                    <div class="form-group password">
                        <div class="input-group">
                            <div class="input-group-addon">
                                <i class="fa fa-lock"></i>
                            </div>
                            <input class="form-control" id="password-input" type="password" autocomplete="off" placeholder=" 请输入密码" name="password">
                        </div>
                        <div class="error" id="user-error"></div>
                    </div>
                    <div class="form-group password">
                        <div class="input-group">
                            <div class="input-group-addon">
                                <i class="fa fa-lock"></i>
                            </div>
                            <input class="form-control" id="valid_input" autocomplete="off" placeholder=" 请输入验证码" name="valid_input">
                           <img src="${ctx }/ValidateCodeServlet" id="img" onclick="changeImg();" />
                            <span style="font-size:10px;"  onclick="changeImg();">更换验证码?</span>
                        </div>
                        <div class="valid_error" id="valid_error"></div>
                    </div>
                   
                    <div class="submit">
                        <input type="button" id="submit" name="submit" value="确认">
                    </div>
                </form>
              <a href="${ctx }/zhuche.jsp"> <p style="position: relative; top:12px;font-size:12px; color:#FF0000;">没有账号?请注册</p></a> 
</div>
</div>

Jquery block

Introducing the first packet of Jquery js (jquery-3.3.1.min.js)

<script src="${ctx }/js/jquery-3.3.1.min.js"></script>

Download: https://www.cnblogs.com/it-tsz/p/10283929.html

The following is the code Jquery Ajax

 

<script type="text/javascript">
function changeImg(){
	var img = document.getElementById("img");
	img.src = "ValidateCodeServlet?a=" +Math.random() ;
}
$(function(){
    var username_error=$("#username-error");
    var user_error = $("#user-error");
    var username_input = $("#username-input");
    var password_input = $("#password-input");
    var valid_input=$("#valid_input");
    var valid_error=$("#valid_error");
    var submit=$("#submit");
    valid_error.hide();
    username_error.hide();   // 把提示框隐藏起来
    user_error.hide();                                
    // 密码检验
    function password_validate(){
        var password = password_input.val();
        
        if(password == ""){
            user_error.html("密码不能为空");
            valid_error.hide();
            user_error.show();
            
        }
        else if(password_input.val().length>15){
            user_error.html("密码长度不能超过15");
            user_error.show();           
        }
        else user_error.hide();
    }
    // 用户名检验
    function username_validate(){
        var username = username_input.val();
        var user = {"username": username};        
        if (username.trim() == "") {
            username_error.html("用户名不能为空");
            user_error.hide(); 
            username_error.show();
            username_input.val("").focus();            
        }
        else  username_error.hide();
    }
    //验证码检验
    function valid_validate(){
        var valid = valid_input.val();
        if(valid == ""){
            valid_error.html("验证码不能为空");
            user_error.hide();
            valid_error.show();           
        }      
        else valid_error.hide();
    }
    // 提交时检验
    function submit_validate(){
        var username = username_input.val();
        var password = password_input.val();
        var valid=valid_input.val();
        var user = {"username": username, "password": password};
        if(username=="" || password==""||valid==""){
            valid_error.html("用户名、密码、验证码不能为空");
            username_error.hide();
            user_error.hide();           
            valid_error.show();
        }
        else{
            var config={
            			"url":"/Shop/LoginServlet",
            			"async":true,
            			"dataType":"text",
            			"type":"post",
            			"data":{
                        	"userName":username,
                        	"password":password,
                        	"valid":valid,
                        },
                        "beforeSend": function(){
                            submit.val("登录中...");
                        },   
                       "success": function(result){
                            if(result=="false"){                           	
                                valid_error.html("账号不存在! 请注册");
                                valid_error.show();
                                submit.val("确认");
                              //刷新验证码
                                changeImg();
                               
                            }
                            else if(result=="null"){
                            	valid_error.html("用户名、密码不能为空");
                                valid_error.show();
                                submit.val("确认");
                              	//刷新验证码
                                changeImg();
                            }
                            else if(result=="validerror"){
                            	valid_error.html("验证码错误");
                                valid_error.show();
                                submit.val("确认"); 
                                
                            }
                            else if(result=="passworderror"){
                            	valid_error.html("密码错误!");
                                valid_error.show();
                                submit.val("确认");
                                //刷新验证码
                                changeImg();
                            }
                            //检验成功,实现跳转
                            else{
                            	window.location.href="/Shop/test/index.jsp";                                
                            }
                        },
                        "error":function(xhr,status,error){
            				
            			}
                        
                    };
            
            $.ajax(config);
        }
        
    }
    valid_input.blur(valid_validate);
    username_input.blur(username_validate);    // 鼠标焦点从用户名移开触发的事件
    password_input.blur(password_validate);    // 鼠标移开密码输入框时触发的事件
    submit.click(submit_validate);             // 单击提交按钮触发的事件
})
</script>

Servlet receives the request

HttpSession session = request.getSession();
		//接收输入的验证码
		String valid=request.getParameter("valid");
        //通过userName获取对应的值
		String userName = request.getParameter("userName");
        //通过password获取对应的值
		String password = request.getParameter("password");
        //获取Session存入的验证码
		String code=(String) session.getAttribute("code");
		//将Service导入
		UserService service=new UserService();
		
		try {
            //进行判断
			if(!code.equals(valid)) {
				response.getWriter().write("validerror");
				return;
			}
            /*调用service中的findUserAll方法
            *先判断用户名,然后判断密码
            */
			int num=service.findUserAll(userName, password);
				//进行判断响应前端
                //当num为1时,说明验证成功
		        if(num==1) {
                    //通过用户名查询出用户id,然后存入Session
					int userId=service.findUserId(userName);
                    //通过用户名查出用户所有的信息,然后存入Session
					User user=service.findAllUserList(userName);
					session.setAttribute("userId", userId);	
					session.setAttribute("userName", userName);
					session.setAttribute("user", user);	
                    //响应到前端							
					response.getWriter().print(true);
					return;
				}
		        else {
                    //当num为0时,返回前端passworderror
		        	if(num==0) {
			        	response.getWriter().write("passworderror");
			        	return;
		              }
                    //当num为-2时,返回前端为null
		        	else if(num==-2) {
		        		response.getWriter().write("null");
		        	}
		        else {
                    //条件都不成立时,返回前端为false
		        	response.getWriter().print(false);
		        	}
				}
		}
		catch(Exception e){
			e.printStackTrace();
            request.setAttribute("message", e.getMessage());
			response.getWriter().print("message");
		}

	}

service layer

UserDao dao=new UserDao();
	/*
	 * 用户登录
	 */
	public int findUserAll(String userName,String password) {
		//把Servlet的用户名和密码传进来
		int num=this.dao.findUserAll(userName,password);
        //对num的结果进行判断
		if(num>0) {
			return 1;
		}
		else {
			if(num==0) {
				return 0;
			}
            else if(num==-2) {
				return -2;
			}
		}
	   return -1;
	}
    /*
	 * 根据用户名返回用户Id
	 */
	public int findUserId(String userName) {
		int num=0;
		num=this.dao.findUserId(userName);
		return num;
	}
    /*
	 * 根据用户名返回用户所有信息
	 */
	public User findAllUserList(String userName) {
		User result = null;
		//判断用户名是否为空
		if(userName  != null || !userName.equals("")) {
			result = (User) this.dao.getAllUser(userName);		
			return result;
		}	
		return result;
	}

Dao layer

private QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
	/*
	 * 登录
	 */
	public int findUserAll(String userName,String password) {
		String sql="select * from user where userName=?";
		int num=0;
		try {
			if(userName==null&& userName.equals("")&& password==null&&password.equals("")) {
				return -2;
			}
			else {
			User user=(User) runner.query(sql, new BeanHandler(User.class),userName);
			
			//判断用户是否存在
			if(user!=null && !user.equals("")) {
				String userpassword=user.getPassword();
				//判断用户密码是否正确
				if(password.equals(userpassword)) {
					return 1;
				}
				else {
					return 0;
				}
				}
			else {
				return -1;
			}
		} 
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return num;
	}
    /*
	 * 根据用户名返回用户ID
	 * Session保存用户ID
	 */
	public int findUserId(String userName) {
		int userId=0;
		String sql="select * from user where userName=?";
		try {
		List<User> list=(List<User>) runner.query(sql, new BeanListHandler(User.class),userName);
		for(User user:list) {
			userId=user.getId();
		}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return userId;	
	}
    /*
	 * 根据用户名查询用户信息
	 */
	public User getAllUser(String userName){
		User list=null;
		String sql="select * from user where userName=?";
		try {
			list=(User) runner.query(sql, new BeanHandler(User.class),userName);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

Specific behind JDBCUtil and C3P0 speak, I remember attention Oh, give praise it.

 

 

Published 10 original articles · won praise 11 · views 599

Guess you like

Origin blog.csdn.net/weixin_44715643/article/details/103913835