日期:2014-05-16  浏览次数:20653 次

struts2通过jquery ajax登陆

登陆页面login.jsp

$.ajax( {
			    url :"<%=basePath%>euser/euser_login.action",
			    type :"post",
			    dataType :"json",
			    data :"username=" + $("#username").val()
			      + "&password=" + $("#password").val() + "&vercode=" + $("#vercode").val(),
			 //   timeout :20000,// 设置请求超时时间(毫秒)。
			    error : function() {// 请求失败时调用函数。
			     $("#loginResult").html("请求失败!");
			    },
			    success :function (data){
				    //alert(data);
				    if(1 == data){
							//alert("登陆成功");
						location.href = "<%=basePath%>euser/euser_indexUI.action" ;
					}else if(2 == data){
						$("#username_Info").html("用户名或者密码错误!");
						$("#username").val("");
						$("#password").val("");
						$("#vercode").val("");
						reloadImg();
					    }else if(4 == data){
							$("#vercode_Info").html("验证码错误!");
							reloadImg();
					}
			    }
			   });

?

Action处理函数

public String login() throws Exception {
		String user_name = (String) getRequest().getParameter("username");
		String pass_word = (String) getRequest().getParameter("password");
		String ver_code = (String) getRequest().getParameter("vercode");
		username = user_name;
		password = pass_word;
		vercode = ver_code;

		Euser EuserForm = new Euser();
		EuserForm.setUsername(username);
		EuserForm.setPassword(password);
		String ver = (String) super.getSession().getAttribute("rand");
		vercode = vercode.trim().toLowerCase();
		super.getSession().setAttribute("rand", null);

		if (null != this.username && !"".equals(this.username.trim())
				&& null != this.password && !"".equals(this.password.trim())) {
			if (null != vercode && !"".equals(vercode) && vercode.equals(ver)) {

				Euser loginEuser = euserService.login(EuserForm);

				if (loginEuser != null) {
					WebUtil.putLoginEuser(super.getRequest(), loginEuser);

					response.setContentType("text/html;charset=UTF-8");
					response.setCharacterEncoding("UTF-8");// 防止弹出的信息出现乱码
					PrintWriter out = response.getWriter();
					out.print(LOGIN_SUCCESS);
					out.flush();
					out.close();
					return null;
				} else {
					response.setContentType("text/html;charset=UTF-8");
					response.setCharacterEncoding("UTF-8");// 防止弹出的信息出现乱码
					PrintWriter out = response.getWriter();
					out.print(LOGIN_USERNAME_ERROR);
					out.flush();
					out.close();
					return null;
				}

			} else {
				response.setContentType("text/html;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");// 防止弹出的信息出现乱码
				PrintWriter out = response.getWriter();
				out.print(LOGIN_VERCODE_ERROR);
				out.flush();
				out.close();
				return null;
			}

		} else {
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");// 防止弹出的信息出现乱码
			PrintWriter out = response.getWriter();
			out.print(LOGIN_USERNAME_ERROR);
			out.flush();
			out.close();
			return null;
		}
	}

?