配置一个权限filter,拦截一切没有登录却想访问只有登录后才有的权限页面的url,我的做法如下:
先写上一个filter:
然后在web.xml中配置,这时我把这个filter的配置放在struts核心filter之前,放在之后貌似起不到你要的效果,这个还需要求解释(貌似是优先级的问题)
这样一配置,我想要拦截访问admin下所有的请求就能够实现了,注意:你的filter一定要写正确,使用filter时避免连续两次跳转,否则会报java.lang.IllegalStateException错误
先写上一个filter:
package com.xll.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RightFilter implements Filter {
private FilterConfig filterConfig;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String uri = request.getRequestURI();
System.out.println(uri);
String ctx = request.getContextPath();
System.out.println(ctx);
uri = uri.substring(ctx.length());
if (uri.startsWith("/admin")) {
if (request.getSession().getAttribute("username") == null) {
System.out.println("没有登录");
response.sendRedirect("/VoteSystem/index.jsp");
System.out.println("xxxxxxxxxxx");
return ;
} else {
chain.doFilter(request, response);
}
}
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
}
然后在web.xml中配置,这时我把这个filter的配置放在struts核心filter之前,放在之后貌似起不到你要的效果,这个还需要求解释(貌似是优先级的问题)
<filter>
<filter-name>RightFilter</filter-name>
<filter-class>com.xll.util.RightFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RightFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
<filter> <!--定义核心Filter FilterDispatcher -->
<filter-name>struts2</filter-name> <!-- 定义核心Filter的名称 -->
<filter-class> <!--定义核心Filter的实现类 -->
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name><!--核心Filter的名称 -->
<url-pattern>/*</url-pattern><!--使用该核心Filter过滤所有的Web请求 -->
</filter-mapping>
这样一配置,我想要拦截访问admin下所有的请求就能够实现了,注意:你的filter一定要写正确,使用filter时避免连续两次跳转,否则会报java.lang.IllegalStateException错误