当前位置:编程学习 > 网站相关 >>

Web权限验证过滤器

本文只是描述了一个比较简单的入门级的权限过滤器

实际上更好的参考实现有两款产品:Apache的Shiro(其前身是JSecurity)和SpringSecurity

下面是Web工程中的web.xml
[html] 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 
    <filter> 
        <filter-name>AuthenticationFilter</filter-name> 
        <filter-class>com.jadyer.Filter.AuthenticationFilter</filter-class> 
        <init-param> 
            <param-name>url</param-name> 
            <param-value>/admin/login.jsp</param-value> 
        </init-param> 
    </filter> 
    <filter-mapping> 
        <filter-name>AuthenticationFilter</filter-name> 
        <url-pattern>/admin/secure/*</url-pattern> 
    </filter-mapping> 
     
    <error-page> 
        <error-code>404</error-code> 
        <location>/WEB-INF/404.html</location> 
    </error-page> 
    <error-page> 
        <error-code>500</error-code> 
        <location>/WEB-INF/500.html</location> 
    </error-page> 
    <error-page> 
        <exception-type>javax.servle.ServletException</exception-type> 
        <location>/WEB-INF/error.html</location> 
    </error-page> 
    <error-page> 
        <exception-type>java.lang.NullPointerException</exception-type> 
        <location>/WEB-INF/error.html</location> 
    </error-page> 
</web-app> 

下面是用于权限验证的过滤器AuthenticationFilter.java
[java] 
package com.jadyer.Filter; 
 
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.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
/**
 * 权限验证
 */ 
public class AuthenticationFilter implements Filter { 
    private String url = "/"; //代表根目录 
 
    public void destroy() {} 
     
    /**
     * 获取web.xml中设定的参数url的值
     * @see 即读取web.xml中的<param-name>url</param-name>
     */ 
    public void init(FilterConfig config) throws ServletException { 
        url = config.getInitParameter("url"); 
    } 
 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
        //这两行的强制类型转换是必不可少的  www.zzzyk.com
        HttpServletRequest req = (HttpServletRequest) request; 
        HttpServletResponse res = (HttpServletResponse) response; 
        //如果是普通用户或者管理员session已过期,则转到指定页面并返回,而不再执行下一个过滤链 
        if (null == req.getSession().getAttribute("guesbook.admin.username")) { 
            res.sendRedirect(req.getContextPath() + url); 
        } else { 
            chain.doFilter(request, response); 
        } 
    } 

补充:Web开发 , 其他 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,