我正在尝试创建一个过滤器,以确保用户在转到其他页面之前已登录
在这里,我有2个问题(我知道)。
1)我只允许jsp文件有问题。 当我尝试访问我的页面时,tomcat引发错误
java.lang.IllegalArgumentException: Invalid <url-pattern> /public/*.jsp in filter mapping
但是当我的网址映射是/ public / *时,它可以按预期工作
2)当我确实获得了重定向时,/public/*我可以进入登录页面,但是所有样式都丢失了
/public/*
这是我在web.xml中的过滤器
EDIT2: 现在下面的代码段反映了我对答案所做的更改
<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>
这就是我在过滤器中尝试的
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); } }
有任何改进我的过滤器的建议吗?
网址格式不是真正的全局匹配,仅支持两种类型的通配符:/someting/*和*.something
/someting/*
*.something
http://www.roguewave.com/portals/0/products/hydraexpress/docs/3.5.0/html/rwsfservletug/4-3.html
涉及样式时,必须允许加载登录页面使用的资源(CSS,Javascript,图像等)而无需会话,这与允许访问登录页面本身的方式相同。