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.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方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |