struts2中的攔截器可以攔截action,但是無法攔截頁面的請求,但是有些頁面需要有權限才可以訪問,不可以直接訪問,有一種解決的辦法就是使用Filter
1、創建Filter類,需要實現Filter接口:
[java]
package filter;
import java.io.IOException;
import java.util.Map;
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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Admin;
public class LoginFilter implements Filter {
//private Map session;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
HttpSession session = request.getSession();
Admin admin = (Admin) session.getAttribute("nowUser");
System.out.println(admin);
if(admin == null){
response.sendRedirect("login.html");
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
在doFilter中實現過濾功能,這裡主要是驗證用戶請求index.html頁面時是否登錄,如果登錄則繼續運行,否則返回到登錄頁面
還需要配置web.xml:添加下面的代碼
[html]
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/index.html</url-pattern>
</filter-mapping>
配置文件的幾種不同的情況:
1、過濾所有的請求:
[html]
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、過濾制定類型的請求:只過濾“.html”的文件
[html]
filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
3、過濾多種類型的:需要配置兩個<filter-mapping>
[html]
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
4、過濾指定文件:就是剛才的情況,注意加“/”
[html]
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/index.html</url-pattern>
</filter-mapping>