如何处理/限制用户对servlet和jsp的访问?
我目前正在用Java编写一个动态的Web应用程序。该应用程序应该是一个事件平台,您可以在其中创建用户帐户,登录,然后查看所有打开的事件(在以后的迭代中,用户可以创建/参与这些事件)。
现在,可以这样描述(简化)Web应用程序的结构:
Register-Servlet -> Register.jsp        |
        V
Login-Servlet -> Login.jsp
        |
        V
Main-page-Servlet -> Main.jsp
因此,现在,用户可以转到Login.jsp,他的登录信息将发送到Login-Servlet,后者将对其进行验证,然后将其发送到Main-Page-
Servlet。然后,Main-Page-
Servlet(再次验证登录名之后)从数据库获取所有当前事件,将其附加到请求,然后将其转发到Main.jsp,后者将其显示给用户查看。
现在,如果用户想直接访问Main.jsp(而不是来自Main-Page-
Servlet),则显然无法显示可用事件。我当前使用的解决方法是进行空检查,以查看事件是否存在,如果不存在,请重定向到Main-Page-Servlet。
这样麻烦我解决我的问题,因为我认为这不是最佳实践,而且我认为随着应用程序的扩大,它只会带来很多其他问题。
我首先想到的是,如果我可以简单地从用户“隐藏”所有.jsp,这可能会很有用,因此用户只能登陆servlet,而不能以其他方式访问.jsp。
有没有办法做到这一点?否则,如果我要编写专业的企业级应用程序,那么最佳实践解决方案是什么?
回答:
这可以在中进行处理,Filter。
在那里修改代码以解决您的问题(注意方法的添加和使用needsAuthentication):
@WebFilter("/*")public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig config)
        throws ServletException {
        // If you have any <init-param> in web.xml, then you could get them
        // here by config.getInitParameter("name") and assign it as field.
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        String requestPath = httpServletRequest.getRequestURI();
        if (needsAuthentication(requestPath) ||
            session == null ||
            session.getAttribute("user") == null) { // change "user" for the session attribute you have defined
            response.sendRedirect(request.getContextPath() + "/login"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }
    @Override
    public void destroy() {
        // If you have assigned any expensive resources as field of
        // this Filter class, then you could clean/close them here.
    }
    //basic validation of pages that do not require authentication
    private boolean needsAuthentication(String url) {
        String[] validNonAuthenticationUrls =
            { "Login.jsp", "Register.jsp" };
        for(String validUrl : validNonAuthenticationUrls) {
            if (url.endsWith(validUrl)) {
                return false;
            }
        }
        return true;
    }
}
我建议将所有需要身份验证的页面移动到一个文件夹中app,然后将网络过滤器更改为
@WebFilter("/app/*")这样,您可以从过滤器中 删除 该needsAuthentication方法。
以上是 如何处理/限制用户对servlet和jsp的访问? 的全部内容, 来源链接: utcz.com/qa/421137.html








