jsp中判断权限,若没有登录,则不能访问

本文介绍了一个使用JSP实现的简单权限过滤器示例。该示例通过判断当前登录用户的用户名是否为admin来决定是否允许访问特定页面。若用户不是管理员,则将跳转至首页。

在jsp中加

<jsp:include page="permission_adminfilter.jsp"/>

permission_adminfilter.jsp中内容如下:

<%@ page language="java" contentType="text/html;charset=GBK" %>
<%
   request.setCharacterEncoding("GBK");
   String loginUserName = (String)session.getAttribute("session_loginname");
   if(!"admin".equals(loginUserName)){
      %>
      <script language="JavaScript" type="text/javascript">
      alert("您无权访问该页面!");
      top.location.href="../index.jsp";
      </script>
      <%  
    }
%>

<think>我们需要实现一个权限控制机制,确保用户在没有登录的情况下无法访问特定的JSP页面。通常,我们会使用过滤器(Filter)来拦截请求,检查用户是否已经登录(通常通过Session中是否存在用户信息来判断)。如果未登录,则重定向到登录页面。 以下是实现步骤: 1. 创建一个过滤器(例如:AuthenticationFilter),用于拦截需要权限控制的请求。 2. 在过滤器中,检查用户是否登录(检查Session中是否有用户对象)。 3. 如果未登录,则重定向到登录页面。 4. 配置过滤器,使其拦截需要权限控制的URL(例如:所有JSP页面,或者特定的路径)。 注意:通常登录页面本身和登录处理的Servlet不需要拦截,否则会导致重定向循环。 下面是一个示例代码: 首先,创建过滤器类 `AuthenticationFilter`:</think># JSP页面权限控制实现方案 要实现JSP页面的权限控制,确保未登录用户无法访问,可以通过以下两种主要方式实现: ## 方案一:使用过滤器(Filter)实现权限控制 这是最推荐的方式,通过过滤器统一拦截请求进行权限验证。 ```java // AuthFilter.java import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebFilter(filterName = "AuthFilter", urlPatterns = {"*.jsp", "/protected/*"}) public class AuthFilter implements Filter { // 需要排除的URL列表(不需要登录即可访问) private static final String[] EXCLUDE_URLS = { "/login.jsp", "/register.jsp", "/error.jsp", "/css/", "/js/", "/images/" }; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; HttpSession session = req.getSession(false); String path = req.getRequestURI().substring(req.getContextPath().length()); // 检查是否在排除列表中 if (isExcluded(path)) { chain.doFilter(request, response); return; } // 检查用户是否已登录 boolean isLoggedIn = (session != null && session.getAttribute("user") != null); if (!isLoggedIn) { // 未登录用户重定向到登录页面 res.sendRedirect(req.getContextPath() + "/login.jsp?redirect=" + URLEncoder.encode(path, "UTF-8")); return; } // 已登录用户继续访问 chain.doFilter(request, response); } private boolean isExcluded(String path) { for (String exclude : EXCLUDE_URLS) { if (path.startsWith(exclude)) { return true; } } return false; } // 其他Filter方法实现... } ``` ## 方案二:在JSP页面顶部添加权限检查 在需要保护的JSP页面顶部添加权限验证代码: ```jsp <%@page import="java.net.URLEncoder" %> <% // 检查用户是否登录 Object user = session.getAttribute("user"); if (user == null) { // 获取当前请求URL String requestURI = request.getRequestURI(); String queryString = request.getQueryString(); String redirectURL = requestURI + (queryString != null ? "?" + queryString : ""); // 重定向到登录页面 response.sendRedirect(request.getContextPath() + "/login.jsp?redirect=" + URLEncoder.encode(redirectURL, "UTF-8")); return; // 停止执行后续页面内容 } %> ``` ## 方案三:使用JSP自定义标签实现权限控制 创建自定义标签库简化权限控制: ```java // AuthTag.java import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.tagext.TagSupport; import java.io.IOException; public class AuthTag extends TagSupport { @Override public int doStartTag() throws JspException { try { Object user = pageContext.getSession().getAttribute("user"); if (user == null) { String redirect = pageContext.getRequest().getRequestURI(); pageContext.getResponse().sendRedirect( pageContext.getServletContext().getContextPath() + "/login.jsp?redirect=" + java.net.URLEncoder.encode(redirect, "UTF-8") ); return SKIP_PAGE; } return EVAL_BODY_INCLUDE; } catch (IOException e) { throw new JspTagException("Error in AuthTag: " + e.getMessage()); } } } ``` 在TLD文件中注册标签: ```xml <!-- WEB-INF/tags.tld --> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>auth</short-name> <uri>/WEB-INF/tags/auth.tld</uri> <tag> <name>requireLogin</name> <tag-class>com.example.AuthTag</tag-class> <body-content>scriptless</body-content> </tag> </taglib> ``` 在JSP中使用: ```jsp <%@ taglib prefix="auth" uri="/WEB-INF/tags/auth.tld" %> <auth:requireLogin /> <!-- 页面内容 --> ``` ## 登录处理Servlet示例 ```java // LoginServlet.java @WebServlet("/login") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); // 验证用户凭证(实际应用中应使用数据库验证) if ("admin".equals(username) && "password".equals(password)) { // 创建会话并存储用户信息 HttpSession session = request.getSession(); session.setAttribute("user", username); // 重定向到原始请求或首页 String redirect = request.getParameter("redirect"); if (redirect != null && !redirect.isEmpty()) { response.sendRedirect(redirect); } else { response.sendRedirect(request.getContextPath() + "/index.jsp"); } } else { // 登录失败,返回登录页 request.setAttribute("error", "无效的用户名或密码"); request.getRequestDispatcher("/login.jsp").forward(request, response); } } } ``` ## 登录页面示例 (login.jsp) ```jsp <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录</title> </head> <body> <h2>请登录</h2> <%-- 显示错误信息 --%> <c:if test="${not empty error}"> <div style="color:red;">${error}</div> </c:if> <form action="${pageContext.request.contextPath}/login" method="post"> <input type="hidden" name="redirect" value="${param.redirect}"> <div> <label>用户名:</label> <input type="text" name="username" required> </div> <div> <label>密码:</label> <input type="password" name="password" required> </div> <button type="submit">登录</button> </form> </body> </html> ``` ## 方案对比 | 方案 | 优点 | 缺点 | 适用场景 | |------|------|------|----------| | **过滤器** | 集中控制,维护方便 | 需要配置排除路径 | 推荐方案,适合所有JSP页面保护 | | **JSP顶部检查** | 简单直接 | 需要在每个页面添加代码 | 少量页面保护 | | **自定义标签** | 可复用,代码简洁 | 需要创建标签库 | 需要复用权限检查逻辑的场景 | ## 最佳实践建议 1. **使用过滤器作为主要方案**:集中管理权限控制逻辑 2. **合理设置会话超时**:在web.xml中配置会话超时时间 ```xml <session-config> <session-timeout>30</session-timeout> <!-- 30分钟 --> </session-config> ``` 3. **安全退出**:提供注销功能 ```jsp <a href="${pageContext.request.contextPath}/logout">退出</a> ``` ```java // LogoutServlet.java @WebServlet("/logout") public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); // 销毁会话 } response.sendRedirect(request.getContextPath() + "/login.jsp"); } } ``` 4. **防止会话固定攻击**:登录成功后重新生成会话ID ```java // 登录成功后 request.getSession().invalidate(); // 使旧会话失效 HttpSession newSession = request.getSession(true); // 创建新会话 newSession.setAttribute("user", username); ``` 5. **使用HTTPS**:保护登录凭证传输安全
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值