微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 如何处理/限制对servlet和jsp的用户访问?

我正在 Java中编写一个动态的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处理,在 StackOverflow Servlet-Filter wiki有很好的解释和例子.

适应您的问题的代码(注意需求的验证方法添加和使用):

@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;
    }
}

我建议将需要身份验证的所有页面移动到像应用程序这样的文件夹中,然后将Web过滤器更改为

@WebFilter("/app/*")

这样,您可以从过滤器中删除needsAuthentication方法.

原文地址:https://www.jb51.cc/java/123136.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐