最初我是在网上找了一个实现无刷新登录的代码,自己稍加改动,就勉强可以用了,当时前台代码如下:
|
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>AJAX实现无刷新登录</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script language="javascript" type="text/javascript"> var XMLHttpReq=false; function createXMLHttpRequest() { //创建xmlhttprequest; if(window.XMLHttpRequest) { //Mozilla 浏览器 XMLHttpReq = new XMLHttpRequest(); }else if (window.ActiveXObject) { // IE浏览器 XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } } function processlogin(){ if (XMLHttpReq.readyState == 4) { // 判断对象状态 if (XMLHttpReq.status == 200) { // 信息已经成功返回,开始处理信息 var xmlDoc = XMLHttpReq.responseXML.documentElement; var node = xmlDoc.getElementsByTagName('info'); showlogined(); document.getElementById('logined').innerHTML=""; for(var i=0;i<node.length;i++){ document.getElementById('logined').innerHTML += node[i].firstChild.nodeValue+'<br>'; } document.getElementById('logined').innerHTML+="<a href='#' onclick='javascript:showlogin();return false'>重新登录</a>"; } else { //页面不正常 window.alert("您所请求的页面有异常。"); } } } function checkuser(){ var name=document.getElementById("username").value; var password=document.getElementById("password").value; if(name==""){ alert("用户名不能为空!"); document.getElementById("username").focus(); return; }else if(password==""){ alert("密码不能为空!"); document.getElementById("password").focus(); return; }else{ createXMLHttpRequest(); var url="login.do?username="+name+"&password="+password; XMLHttpReq.onreadystatechange= processlogin; XMLHttpReq.open("GET",url,true); XMLHttpReq.send(null); } } function showlogin(){ document.getElementById('login').style.display='block'; document.getElementById('logined').style.display='none'; } function showlogined(){ document.getElementById('login').style.display='none'; document.getElementById('logined').style.display='block'; } </script> </head> <body> <div id="logined"></div> <div id="login"> <table align=left width=600 border=0> <tr> <td> 用户名: </td> <td> <input type="text" size="20" id="username"> </td> </tr> <tr> <td> 密码: </td> <td> <input type="password" size="20" id="password"> </td> </tr> <tr> <td> <input type="button" value="登陆" onclick="checkuser();"> </td> </tr> </table> </div> </body> </html>
|
后台代码(struts1.2)我是这样写的
|
package struts.action;
import hibernate.*;
import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping;
public class loginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("utf-8"); response.setContentType("text/xml;charset=utf-8"); response.setHeader("Cache-Control", "no-cache"); String name = request.getParameter("username"); String password = request.getParameter("password"); TeacherDAO userDao = new TeacherDAO(); List list = (List) userDao.findByUsername(name); String xml_head = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; String xml_start = "<message>"; String xml; String xml_end = "</message>"; if(list.isEmpty()){ xml="<info>用户名不存在</info>"; request.getSession().setAttribute("logininfo","用户名不存在"); }else{ Teacher user=(Teacher)list.get(0); if(user.getPassword().equals(password)){ xml = "<info>登录成功</info>"; xml += "<info>用户名:" + user.getUsername() + "</info>"; xml += "<info>真实姓名:" + user.getRealname() + "</info>"; xml += "<info>用户信息:" + user.getUserinfo() + "</info>"; request.getSession().setAttribute("logininfo", "登录成功"); request.getSession().setAttribute("username", user.getUsername()); request.getSession().setAttribute("realname", user.getRealname()); request.getSession().setAttribute("userinfo", user.getUserinfo()); }else{ xml = "<info>密码错误</info>"; request.getSession().setAttribute("logininfo", "密码错误"); } } response.getWriter().write(xml_head+xml_start+xml+xml_end); return null; } }
|
这样就实现了不刷新登录,但是又一个缺点:比如,你已经登录了,网页会显示你的登录信息
也就是logined面板被激活显示出来了,login面板被隐藏了。可是当你在刷新网页时,你会发现你又回到了login面板,也就是你又回到了登录页面。其实这是因为javascript不能保存状态的原因,虽然此时使用${sessionScope.username}可以获取值,但是javascript不是通过他来改变状态的!这件事我郁闷了好久才解决了问题。
下面我就把我改进后的代码公布出来,写的不好,见谅:(后台不变)
|
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>AJAX实现无刷新登录</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script language="javascript" type="text/javascript"> var XMLHttpReq=false; function createXMLHttpRequest() { //创建xmlhttprequest; if(window.XMLHttpRequest) { //Mozilla 浏览器 XMLHttpReq = new XMLHttpRequest(); }else if (window.ActiveXObject) { // IE浏览器 XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } } function processlogin(){ if (XMLHttpReq.readyState == 4) { // 判断对象状态 if (XMLHttpReq.status == 200) { // 信息已经成功返回,开始处理信息 var xmlDoc = XMLHttpReq.responseXML.documentElement; var node = xmlDoc.getElementsByTagName('info'); showlogined(); document.getElementById('logined').innerHTML=""; for(var i=0;i<node.length;i++){ document.getElementById('logined').innerHTML += node[i].firstChild.nodeValue+'<br>'; } if(node.length==1){ document.getElementById('logined').innerHTML+="<a href='#' onclick='javascript:loginout();return false'>重新登录</a>"; }else if(node.length==4){ document.getElementById('logined').innerHTML+="<a href='#' onclick='javascript:loginout();return false'>退出</a>"; } } else { //页面不正常 window.alert("您所请求的页面有异常。"); } } } function checkuser(){ var name=document.getElementById("username").value; var password=document.getElementById("password").value; if(name==""){ alert("用户名不能为空!"); document.getElementById("username").focus(); return; }else if(password==""){ alert("密码不能为空!"); document.getElementById("password").focus(); return; }else{ createXMLHttpRequest(); var url="login.do?username="+name+"&password="+password; XMLHttpReq.onreadystatechange= processlogin; XMLHttpReq.open("GET",url,true); XMLHttpReq.send(null); } } function loginout(){ createXMLHttpRequest(); var url="loginout.do"; XMLHttpReq.onreadystatechange= showlogin; XMLHttpReq.open("GET",url,true); XMLHttpReq.send(null); } function showlogin(){ document.getElementById('login').style.display='block'; document.getElementById('logined').style.display='none'; } function showlogined(){ document.getElementById('login').style.display='none'; document.getElementById('logined').style.display='block'; } function init(){ if('${sessionScope.username}'!=""){ showlogined(); document.getElementById('logined').innerHTML = '${sessionScope.logininfo}'+'<br>'; document.getElementById('logined').innerHTML += '用户名:'+'${sessionScope.username}'+'<br>'; document.getElementById('logined').innerHTML += '真实姓名:'+'${sessionScope.realname}'+'<br>'; document.getElementById('logined').innerHTML += '用户信息:'+'${sessionScope.userinfo}'+'<br>'; document.getElementById('logined').innerHTML +="<a href='#' onclick='javascript:loginout();return false'>退出</a>"; } } </script> </head> <body onload="init()"> <div id="logined"></div> <div id="login"> <table align=left width=600 border=0> <tr> <td> 用户名: </td> <td> <input type="text" size="20" id="username"> </td> </tr> <tr> <td> 密码: </td> <td> <input type="password" size="20" id="password"> </td> </tr> <tr> <td> <input type="button" value="登陆" onclick="checkuser();"> </td> </tr> </table> </div> </body> </html>
|
退出(重新登录)后台代码如下:
|
package struts.action;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping;
public class LoginoutAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { request.getSession().invalidate(); return null; } }
|
struts-config.xml文件内的主要代码如下:
|
<action-mappings> <action path="/login" type="struts.action.loginAction" />
<action path="/loginout" type="struts.action.LoginoutAction" /> </action-mappings>
|
|
|