关于使用过滤器设置权限:

关于使用过滤器设置权限:
    过滤器,其实就是一个面向切面编程的很好例子,设置一个切点Pointcut,然后再前面后面加上需要的动作。像编码问题也可以使用到Filter作为统一的过滤。
接下来就简单写一个例子:
首先设置好页面:
index.jsp-->包含欢迎信息!,连接后台,注销等链接;
login.jsp-->
admin/ad_index.jsp
然后写好自定义的Filter类:LimitsFilter(权限设定)登录之后才能进入后台
public class LimitsFilter implements Filter{

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
		    FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
	    HttpServletResponse res = (HttpServletResponse) response;
	    HttpSession session = req.getSession();
	    //从session中取出用户名
	    String username = (String) session.getAttribute("username");
	    //如果没有取到用户名,就跳转到登陆页面
	    if (username == null || "".equals(username)) {
	      //跳转到登陆页面
	      res.sendRedirect("../login.jsp");
	    }
	    else {
	      //已经登陆,继续此次请求
	    	filterChain.doFilter(request,response);
	    }
	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
	@Override
	public void destroy() {
	}
}

然后设定xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<filter>
		<description>权限过滤器</description>
		<filter-name>Limitsfilter</filter-name>
		<filter-class>
			com.LimitsFilter
		</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>Limitsfilter</filter-name>
		<url-pattern>/admin/ad_index.jsp</url-pattern>
	</filter-mapping>
	<servlet>
	    <servlet-name>UserServlet</servlet-name>
	    <servlet-class>com.UserServlet</servlet-class>
  	</servlet>
  	<servlet-mapping>
    	<servlet-name>UserServlet</servlet-name>
    <url-pattern>/UserServlet</url-pattern>
  	</servlet-mapping>
  	<welcome-file-list>
    	<welcome-file>index.jsp</welcome-file>
  	</welcome-file-list>
</web-app>

你可能感兴趣的:(编程语言,filter,J2EE,过滤器,权限管理)