Question

I am trying to create a filter that makes sure the user is logged in before going to any other page

Here I have 2 issues (that I know of).

1) I am having issues with only allowing jsp files. When I try to access my page tomcat throws an error

 java.lang.IllegalArgumentException: Invalid <url-pattern> /public/*.jsp in filter mapping

but when my url mapping is /public/* it sorta works as intended

EDIT 1: Turns out I am using an incorrect mapping, thanks to some comments below, for anyone coming to this page here is that part of the solution: http://www.roguewave.com/portals/0/products/hydraexpress/docs/3.5.0/html/rwsfservletug/4-3.html

2) When I did get a redirect with /public/* I was able to get to my login page, but all of the styling was missing

Here is my filter in web.xml

EDIT2: The code snippets below now reflect changes I have made regarding answers

<filter> <filter-name>LoginFilter</filter-name> <filter-class>authentication.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>

This is what I am attempting in my filter

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);
        // Get the requested address
        String from = URLEncoder.encode(req.getRequestURI(), "UTF-8");

        if(req.getQueryString() != null){
            from += "?" + req.getQueryString();
        }
        System.err.println("from str: " + from);
        System.out.println("Serv path: " + req.getServletPath());
        if(!req.getServletPath().startsWith("/public/login")){
            if(session == null || session.getAttribute("username") == null){
                res.sendRedirect(req.getContextPath() + "/public/login.jsp?from="+from);
            }else{
                System.out.println("Username: " + session.getAttribute("username"));
                // pass the request along the filter chain
                chain.doFilter(request, response);
            }
        }else{
            chain.doFilter(request, response);
        }
    }

Any suggestions for improvements to my filter?

Was it helpful?

Solution

URL pattern is not a true glob match and only supports two types of wildcards: /someting/* and *.something

http://www.roguewave.com/portals/0/products/hydraexpress/docs/3.5.0/html/rwsfservletug/4-3.html

When it comes to styling you have to allow the resources (CSS, Javascript, images etc) used by the login page to be loaded without a session the same way you allow access to the login page itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top