如何处理/限制用户访问servlet& JSP的? [英] How can I handle/restrict user-access to servlets & jsp's?

查看:203
本文介绍了如何处理/限制用户访问servlet& JSP的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用Java编写一个小型的动态Web应用程序。
应用程序应该是一个事件平台,您可以在其中创建用户帐户,登录,然后您可以查看所有打开的事件(在以后的迭代中,用户可以创建/参与这些事件)。



现在,web-app的结构可以(简化)描述如下:

  Register-Servlet  - > Register.jsp 
|
V
登录 - Servlet - > Login.jsp
|
V
主页 - Servlet - > Main.jsp

所以现在,用户可以去Login.jsp,他的登录信息会被发送到Login-Servlet,它将验证它,然后将其发送到Main-Page-Servlet。
然后,Main-Page-Servlet(在再次验证登录之后)从数据库获取所有当前事件,将其附加到请求,并将其转发到Main.jsp,Main.jsp显示它供用户查看。 / p>

现在,如果用户想直接访问Main.jsp(没有来自Main-Page-Servlet),它显然无法显示可用事件。我正在使用的解决方法是进行空检查以查看事件是否存在,如果没有,则重定向到Main-Page-Servlet。



它困扰我解决我的问题,因为我不认为这是最好的做法,我认为它会产生很多其他问题,我的应用程序越大。



<我首先想到的是,如果我可以简单地隐藏用户的所有.jsp,那么用户只能登陆servlet并且无法以不同的方式访问.jsp。



有没有办法做到这一点?或者,如果不是,如果我要编写一个专业的企业级应用程序,最佳实践解决方案是什么?

解决方案

这个可以在 Filter StackOverflow Servlet-Filter wiki 中有很多解释和示例。



根据您的问题调整代码(请注意 needsAuthentication 方法的添加和使用):

  @WebFilter(/ *)
公共类LoginFilter实现过滤器{
@Override
public void init(FilterConfig config)
throws ServletException {
//如果你有任何< init-param>在web.xml中,然后你可以通过config.getInitParameter(name)获取它们
//并将其指定为字段。
}

@Override
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)
抛出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){//更改userfor您定义的会话属性

response.sendRedirect(request.getContextPath()+/ login); //未找到登录用户,因此重定向到登录页面。
} else {
chain.doFilter(req,res); //找到登录用户,所以继续请求。
}
}

@Override
public void destroy(){
//如果您已将任何昂贵的资源指定为
的字段//这个Filter类,然后你可以在这里清理/关闭它们。
}

//不需要认证的页面的基本验证
private boolean needsAuthentication(String url){
String [] validNonAuthenticationUrls =
{ Login.jsp,Register.jsp};
for(String validUrl:validNonAuthenticationUrls){
if(url.endsWith(validUrl)){
return false;
}
}
返回true;
}
}

我建议移动所有需要身份验证的页面在 app 之类的文件夹中,然后将网络过滤器更改为

  @ WebFilter(/ app / *)

通过这种方式,你可以删除 needsAuthentication 方法。


I'm currently writing a little dynamic web-application in Java. The application is supposed to be an event-platform where you can create a user-account, log in, and then you can see all open events (in a later iteration, users can create/participate in those events).

Right now, the structure of the web-app could be (simplified) described like this:

Register-Servlet -> Register.jsp
        |
        V
Login-Servlet -> Login.jsp
        |
        V
Main-page-Servlet -> Main.jsp

So right now, a user could go to Login.jsp, his login-information would be sent to the Login-Servlet, which would validate it and then send it to the Main-Page-Servlet. The Main-Page-Servlet then (after validating login again) gets all current events from a database, attaches it to the request, and forwards it to the Main.jsp, which displays it for the user to see.

Now, if a user wants to access the Main.jsp directly (without coming from the Main-Page-Servlet), it obviously can not display the available events. The workaround I'm using currently is doing a null-check to see if the events are there, and if not, redirect to the Main-Page-Servlet.

It bothers me to solve my problem like that, as I don't think that's the best practice and I think it will just create a lot of other problems the bigger my application gets.

My first thought about this was, that it might be useful if I could simply "hide" all .jsp's from the user, so the user would be landing on servlets only and could not access the .jsp's in a different way.

Is there a way to do that? Or, if not, what would be the best practice solution if I would be writing a professional enterprise-level application?

解决方案

This can be handled in a Filter and there are great explanation and example in StackOverflow Servlet-Filter wiki.

Adapting the code there for your problem (note the addition and usage of the needsAuthentication method):

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

I would recommend to move all the pages that require authentication inside a folder like app and then change the web filter to

@WebFilter("/app/*")

In this way, you can remove the needsAuthentication method from the filter.

这篇关于如何处理/限制用户访问servlet&amp; JSP的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆