如何解决xxxsearch.jsp登录后搜索跳转及登出未拦截的权限问题
问题分析与修复方案
原代码的核心问题
- 逻辑判断错误:使用按位与
&而非逻辑与&&,导致条件判断不符合预期 - 授权状态管理缺失:登录成功后未正确标记授权状态,登出时未清除授权标记
- 无效代码:
location()调用无意义,跳转后未终止后续代码执行 - 未定义变量:
icount和incrementCount()未声明,可能引发报错中断逻辑
修复后的权限控制代码
$(document).ready(function() { const searchParams = new URLSearchParams(window.location.search); const isAuthorized = localStorage.getItem("someVarKey") === "true"; // 核心权限判断:未授权且无rwUrl参数时跳转登录 if (!isAuthorized && !searchParams.has("rwUrl")) { localStorage.setItem("someVarKey", "false"); window.location.replace("http://localhost:8080/adminlogin.jsp"); return; // 跳转后终止代码执行,避免后续逻辑干扰 } // 若需保留tester参数相关逻辑,请先声明icount变量和incrementCount函数 // if (typeof icount !== 'undefined' && icount === 0 && searchParams.has("tester")) { // incrementCount(); // window.location.replace("http://localhost:8080/login?rwUrl=variable"); // return; // } });
配套登录/登出逻辑调整
登录成功时(adminlogin.jsp):
在登录验证通过后添加代码,标记授权状态并跳回原页面:// 验证用户名密码通过后执行 localStorage.setItem("someVarKey", "true"); // 从URL参数获取原搜索页面地址,无参数则跳转到默认页 const rwUrl = new URLSearchParams(window.location.search).get("rwUrl"); window.location.replace(rwUrl || "http://localhost:8080/");登出时:
在登出按钮的点击事件中清除授权状态:$("#logoutBtn").click(function() { localStorage.removeItem("someVarKey"); window.location.replace("http://localhost:8080/adminlogin.jsp"); });
问题解决说明
- 搜索按钮不再跳转登录:登录成功后
someVarKey被设为"true",权限判断时isAuthorized为真,不会触发跳转逻辑,即使搜索时无rwUrl参数也能正常访问。 - 登出后自动拦截:登出时清除了
localStorage中的授权标记,再次访问搜索页面时isAuthorized为假,且无rwUrl参数,会自动跳转到登录页。
内容的提问来源于stack exchange,提问作者Rahul_profile_03
相关产品推荐
相关产品推荐

