开发者

Am i doing the Servlet-Filter correctly?

开发者 https://www.devze.com 2023-03-10 04:18 出处:网络
Good day! I am trying to disable access on pages that are not part of successful login. I stored the login username in a session so that i could determine if the session is null or not.

Good day!

I am trying to disable access on pages that are not part of successful login. I stored the login username in a session so that i could determine if the session is null or not.

I have several pages so I've decided to create a filter in xml and filter servlet so I don't need to put the if(session == null) code on all the pages.

My code in servlet is as follows:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here
            HttpServletRequest req = (HttpServletRequest)request;
            HttpServletResponse res = (HttpServletResponse)response;

            HttpSession session = req.getSession(false);
            RequestDispatcher rd;

            //need to get the servlet path
            String url = req.getServletPath();
            if( url.equals("/LoginServlet") || url.equals("/LogoutServlet") || url.equals("/login.html") ){
                chain.doFilter(request, response);
            } else {
                if(session == null){
                    rd = req.getRequestDispatcher("index.html");
                    rd.forward(req, res);
                } else {
                    chain.doFilter(request,response);
                }
            }
    }

and my xml filter is as follows:

<filter>
    <disp开发者_Go百科lay-name>sessionFilter</display-name>
    <filter-name>sessionFilter</filter-name>
    <filter-class>com.test.demoSession.filter.sessionFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>sessionFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</filter>

The problem is...

  1. I still can access other servlets without going to the log-in screen. What is the problem with my code.
  2. How can i do this better?


You're only checking if the session has been created, not if the user has been logged in. This is wrong. The session can already be created long before the user logs in.

When you login an user, you should set it as a session attribute

request.getSession().setAttribute("user", user);

In the filter you should check on that instead

User user = (User) request.getSession().getAttribute("user");

if (user == null) {
    // Not logged in.
} else {
    // Logged in.
}

See also:

  • Our Servlet-Filters wiki page
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号