大唐任务管理系统--用过滤器控制用户访问权限

//java代码
package filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import domain.Admin;
import domain.Governor;
import domain.Staff;
/**
* 用过滤器控制用户的访问权限
* @author 何博
*
*/
public class RightsFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest sreq, ServletResponse sres,
FilterChain chain) throws IOException, ServletException {

// 获取uri地址
HttpServletRequest request = (HttpServletRequest) sreq;
HttpServletResponse response = (HttpServletResponse)sres;

// 获取请求的uri,如“/cattsoft/jsp/admin/admin.jsp”
String uri = request.getRequestURI();
String ctx = request.getContextPath();
uri = uri.substring(ctx.length());
System.out.println("uri=="+uri);

// 判断admin(系统管理员)前面是Action请求,后面是页面
if (uri.startsWith("/admin.do") || uri.startsWith("/jsp/admin/")) {
Admin admin = (Admin) request.getSession().getAttribute("admin");
if (admin == null) {
request.setAttribute("message", "对不起,您没有该权限");
request.getRequestDispatcher("/jsp/login.jsp").forward(sreq,sres);
return;
}
}

// 判断governor(主管)
if (uri.startsWith("/governor.do") || uri.startsWith("/jsp/governor/")) {
Governor governor = (Governor) request.getSession().getAttribute("governor");
if (governor == null) {
request.setAttribute("message", "对不起,您没有该权限");
request.getRequestDispatcher("/jsp/login.jsp").forward(sreq,sres);
return;
}
}

// 判断staff(员工)
if (uri.startsWith("/staff.do") || uri.startsWith("/jsp/staff/")) {
Staff staff = (Staff) request.getSession().getAttribute("staff");
if (staff == null) {
request.setAttribute("message", "对不起,您没有该权限");
request.getRequestDispatcher("/jsp/login.jsp").forward(sreq,sres);
return;
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
}

}
//////////////////////////////////////////////////////////////////
//web.xml里的配置
<filter>
<filter-name>RightsFilter</filter-name>
<filter-class>filter.RightsFilter</filter-class>
</filter>
//对请求admin文件夹下面的jsp页面进行过滤
<filter-mapping>
<filter-name>RightsFilter</filter-name>
<url-pattern>/jsp/admin/*</url-pattern>
</filter-mapping>
//对请求governor文件夹下面的jsp页面进行过滤
<filter-mapping>
<filter-name>RightsFilter</filter-name>
<url-pattern>/jsp/governor/*</url-pattern>
</filter-mapping>
//对请求staff文件夹下面的jsp页面进行过滤
<filter-mapping>
<filter-name>RightsFilter</filter-name>
<url-pattern>/jsp/staff/*</url-pattern>
</filter-mapping>
//对请求admin.do进行过滤。例如:admin.do?method=list1
<filter-mapping>
<filter-name>RightsFilter</filter-name>
<url-pattern>/admin.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>RightsFilter</filter-name>
<url-pattern>/governor.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>RightsFilter</filter-name>
<url-pattern>/staff.do</url-pattern>
</filter-mapping>
总结:当然这种方法有一定的局限性,如果想要分配某个角色的具体权限(增,删,该,查),就比较麻烦了。比如下一个项目里面要用得到的,鄙人正在研究中。但是对于非法访问页面很方便的。 期待大家的意见!

你可能感兴趣的:(jsp,Web,servlet,项目管理,配置管理)