免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1171 | 回复: 0
打印 上一主题 下一主题

无刷新登录出现的一点小问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-08-22 08:19 |只看该作者 |倒序浏览



最初我是在网上找了一个实现无刷新登录的代码,自己稍加改动,就勉强可以用了,当时前台代码如下:
%@ 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">
        
    -->
        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;inode.length;i++){
                            document.getElementById('logined').innerHTML += node.firstChild.nodeValue+'
';
                        }
                        document.getElementById('logined').innerHTML+="重新登录";
                    } 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 = "";
        String xml_start = "";
        String xml;
        String xml_end = "";
        if(list.isEmpty()){
            xml="用户名不存在";
            request.getSession().setAttribute("logininfo","用户名不存在");
        }else{
            Teacher user=(Teacher)list.get(0);
            if(user.getPassword().equals(password)){
                xml = "登录成功";
                xml += "用户名:" + user.getUsername() + "";
                xml += "真实姓名:" + user.getRealname() + "";
                xml += "用户信息:" + user.getUserinfo() + "";
                request.getSession().setAttribute("logininfo", "登录成功");
                request.getSession().setAttribute("username", user.getUsername());
                request.getSession().setAttribute("realname", user.getRealname());
                request.getSession().setAttribute("userinfo", user.getUserinfo());
            }else{
                xml = "密码错误";
                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">
        
    -->
        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;inode.length;i++){
                            document.getElementById('logined').innerHTML += node.firstChild.nodeValue+'
';
                        }
                        if(node.length==1){
                            document.getElementById('logined').innerHTML+="重新登录";
                        }else if(node.length==4){
                            document.getElementById('logined').innerHTML+="退出";
                        }
                    } 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}'+'
';
                       document.getElementById('logined').innerHTML += '用户名:'+'${sessionScope.username}'+'
';
                       document.getElementById('logined').innerHTML += '真实姓名:'+'${sessionScope.realname}'+'
';
                       document.getElementById('logined').innerHTML += '用户信息:'+'${sessionScope.userinfo}'+'
';
                       document.getElementById('logined').innerHTML +="退出";
                   }
               }
        /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" />
       ="/loginout" type="struts.action.LoginoutAction" />
/action-mappings>


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/44420/showart_364989.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP