日期:2014-05-17 浏览次数:20718 次
//获取请求路径 String url = request.getRequestURI(); if(url.contains("你要限制的路径")){ //这里做操作 }
------解决方案--------------------
1.直接在XML里面配置filter
<filter>
<filter-name>PopedomFilter</filter-name>
<filter-class>com.wepull.hrms.filter.PopedomFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PopedomFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.写Filter,即上面配置的com.wepull.hrms.filter.PopedomFilter这个类
package com.wepull.hrms.filter;
import java.io.IOException;
import java.util.List;
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;
import javax.servlet.http.HttpSession;
import com.wepull.hrms.util.UserDTO;
public class PopedomFilter implements Filter{
//此处导包是import javax.servlet.Filter
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
//1.处理参数
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
//2.拦截url
String path = request.getRequestURI();
System.out.println("path:"+path);
int index = path.indexOf("/");
String url = path.substring(index+1);
url = url.substring(url.indexOf("/")+1);
System.out.println("url:"+url);
if(url.contains(".jsp")||url.contains(".html")||url.contains(".htm")||url.contains(".gif")||url.contains(".jpg")
||url.contains(".css")||url.contains(".js")||url.contains("doLogin") || url.contains("")) {
chain.doFilter(request, response);
return;
}
//权限拦截:1.判断是否登录 2.看是否有权限
HttpSession session = request.getSession();
UserDTO dto = (UserDTO)session.getAttribute("USER");
if(dto==null) {//没有登录,重新返回登录页面
response.sendRedirect("/HRMS/login.html");
return;
} else {//如果登录成功
List<String> urls = dto.getUrls();
if(urls!=null && urls.size()>=1) {
//看是否拥有当前的权限(url)
System.out.println(urls.contains(url));
if(urls.contains(url)) {
chain.doFilter(request, response);//放行
return;
}else {
response.sendRedirect("/HRMS/error.jsp");
}
}
}
}
public void init(FilterConfig arg0) throws ServletExce