转载:http://www.javaeye.com/topic/95432
众所周知,如果没有对页面进行权限控制,用户只要输入URL就能进入任何页面。
下面就演示一下最基本的使用Fiter来控制页面的权限。
1.写一个FILTER,用来判断用户是否有权限进入指定页面。
java 代码
- 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.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
-
- import org.apache.log4j.Logger;
-
- import com.kiral.action.UserAction;
- import com.kiral.model.User;
-
-
-
-
-
-
-
-
- public class FilterServlet extends HttpServlet implements Filter {
- private static final long serialVersionUID = 5162189625393315379L;
-
- private static Logger LOG = Logger.getLogger(FilterServlet.class);
-
-
-
-
- private String allowRole = null;
-
-
-
-
- private String redirectURl = null;
-
- public void init(FilterConfig filterConfig) throws ServletException {
-
- allowRole = filterConfig.getInitParameter("allowRole");
-
- redirectURl = "/locker/index.html";
- }
-
-
-
-
- public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
- FilterChain filterChain) throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) sRequest;
- HttpServletResponse response = (HttpServletResponse) sResponse;
- HttpSession session = request.getSession();
-
-
- if (session.getAttribute(UserAction.CURRENT_USER) == null) {
- response.sendRedirect(redirectURl);
- }
-
- else {
- User user = (User) session.getAttribute(UserAction.CURRENT_USER);
- try {
-
- if ("0".equals(allowRole) || user.hasPower(allowRole)) {
- filterChain.doFilter(sRequest, sResponse);
- } else {
-
- response.sendRedirect(redirectURl);
- }
- } catch (Throwable e) {
- LOG.error("权限过滤时候出现错误", e);
- throw new RuntimeException("权限过滤时候出现错误", e);
- }
- }
- }
-
- public void destroy() {
- }
-
- }
在web.xml中配置 要过滤的页面和能进入当前页面的角色
xml 代码
-
- <filter>
- <filter-name>UserAdminfilter-name>
-
- <filter-class>com.emap.web.FilterServletfilter-class>
-
- <init-param>
-
- <param-name>allowRoleparam-name>
- <param-value>1param-value>
- init-param>
- filter>
- <filter-mapping>
- <filter-name>UserAdminfilter-name>
- <url-pattern>/jsp/security/*url-pattern>
- filter-mapping>
上面配置的意思是说,当用户进入/jsp/security文件夹下的页面的时候,程序会进入FilterServlet 里的doFilter方法里,进行权限判断。
其他的页面权限控制:
1.你可以在filter里判断用户是否登录,然后需要特殊权限能访问的页面,在页面里进行判断。
2.推荐使用开源框架ACEGI来进行权限控制
|