Java 如何让两个过滤器相互配合使用

Java 如何让两个过滤器相互配合使用,java,servlet-filters,Java,Servlet Filters,我已经写了2个过滤器,1个用于普通用户,1个用于管理员,但你必须是管理员才能登录。以下是我的两个过滤器的来源: public class newFilter implements Filter { String UUIDInDB; String UUIDInCookie; public void init(FilterConfig filterConfig) throws ServletException { //To change body of implemented method

我已经写了2个过滤器,1个用于普通用户,1个用于管理员,但你必须是管理员才能登录。以下是我的两个过滤器的来源:

public class newFilter implements Filter {
String UUIDInDB;
String UUIDInCookie;

public void init(FilterConfig filterConfig) throws ServletException {
    //To change body of implemented methods use File | Settings | File Templates.
}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse res = (HttpServletResponse) servletResponse;

    Cookie[] cookies = req.getCookies();

    UUIDInCookie = getCookieValue(cookies,"pubweb", "noCookie");

    if(UUIDInCookie.equals("noCookie")){
        Cookie cookie = new Cookie("pubweb","noCookie");
        cookie.setMaxAge(1);
        res.addCookie(cookie);
        res.sendRedirect("../Login.jsp");
        return ;
    }

    checkDatabase();

    if(UUIDInCookie.equals(UUIDInDB)){
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("Is allowed thorugh");
    } else if(UUIDInCookie.equals("noCookie")){
        res.sendRedirect("../Login.jsp");
        System.out.println("Isn't allowed thorugh");            
    } else {
        res.sendRedirect("../Login.jsp");
        System.out.println("Isn't allowed thorugh");
    }
}

public void destroy() {
    //To change body of implemented methods use File | Settings | File Templates.
}

public void checkDatabase(){
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

    /*
    The next lines allow you to change the username and password for the password.
    */
    String username = "username";
    String password = "password";

    /*
    The following line is the url. This can be changed to bring in to line with the database.
     */
    String dbURL = "jdbc:mysql://localhost/hpsgdb?user="
            + username + "&password=" + password;
    /*
    This line connects to the database to the information presented earlier.
    */

    java.sql.Connection myConnection = null;
    try {
        myConnection = DriverManager.getConnection(dbURL);
        System.out.println("Connected to Database.");
    } catch (SQLException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
    /*
    The next line creates a query on the database. The query is that you want exacuted is on the next line.
     */
    Statement stat = null;
    try {
        stat = (Statement) myConnection.createStatement();
    } catch (SQLException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    } catch (NullPointerException e){
        e.printStackTrace();
    }

    try {
        ResultSet rs;
        rs = stat.executeQuery("SELECT * from uuid where uuid='" + UUIDInCookie + "';");
        System.out.println("Executed Query.");
        int count = 0;
        while(rs.next())
        UUIDInDB = rs.getString("uuid") ;
        System.out.println(UUIDInDB);
        rs.close();
        myConnection.close();
    } catch (SQLException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    } catch (NullPointerException e){
        e.printStackTrace();
    }
}

public static String getCookieValue(Cookie[] cookies,
                                    String cookieName,
                                    String defaultValue) throws IOException {
    int length = cookies.length;
    System.out.println(length);
    try{
    for(int i=0; i<length; i++) {
        Cookie cookie = cookies[i];
        if (cookieName.equals(cookie.getName())) {
            System.out.println(cookies.length);
            return(cookie.getValue());
        } else {
            return defaultValue;
        }
    } } catch (NullPointerException e){
        e.printStackTrace();
        HttpServletResponse res = null;
        res.sendRedirect("../Login.jsp");
    }
    return(defaultValue);
} 
}
其他过滤器:

public class adminFilter implements Filter {
String UUIDInDB;
String UUIDInCookie;
int role;

public void destroy() {
}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse res = (HttpServletResponse) servletResponse;

    Cookie[] cookies = req.getCookies();

    UUIDInCookie = getCookieValue(cookies,"pubweb", "noCookie");
   // role = Integer.parseInt(getCookieValue(cookies,"pubwebRole", "2"));

    if(UUIDInCookie.equals("noCookie")){
        Cookie cookie = new Cookie("pubweb","noCookie");
        cookie.setMaxAge(1);
        res.addCookie(cookie);
        res.sendRedirect("../Login.jsp");
        return ;
    }

    checkDatabase();

    if(UUIDInCookie.equals(UUIDInDB) && role == 1){
        chain.doFilter(servletRequest, servletResponse);
    } else if(UUIDInCookie.equals("noCookie")){
        res.sendRedirect("../Login.jsp");
    } else if (role == 2){
        res.sendRedirect("/");
    }   else {
        res.sendRedirect("../Login.jsp");
    }
}

public void init(FilterConfig config) throws ServletException {

}

public void checkDatabase(){
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }

    /*
    The next lines allow you to change the username and password for the password.
    */
    String username = "username";
    String password = "password";

    /*
    The following line is the url. This can be changed to bring in to line with the database.
     */
    String dbURL = "jdbc:mysql://localhost/hpsgdb?user="
            + username + "&password=" + password;
    /*
    This line connects to the database to the information presented earlier.
    */

    java.sql.Connection myConnection = null;
    try {
        myConnection = DriverManager.getConnection(dbURL);
        System.out.println("Connected to Database.");
    } catch (SQLException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    }
    /*
    The next line creates a query on the database. The query is that you want exacuted is on the next line.
     */
    Statement stat = null;
    try {
        stat = (Statement) myConnection.createStatement();
    } catch (SQLException e) {
        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
    } catch (NullPointerException e){
        e.printStackTrace();
    }

    try {
        ResultSet rs;
        rs = stat.executeQuery("SELECT * from uuid where uuid='" + UUIDInCookie + "';");
        System.out.println("Executed Query.");
        int count = 0;
        while(rs.next()) {
        UUIDInDB = rs.getString("uuid") ;
        role = rs.getInt("role");
        }
        System.out.println(UUIDInDB);
        System.out.println("Role =" + role);
        rs.close();
        myConnection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (NullPointerException e){
        e.printStackTrace();
    }
}

public static String getCookieValue(Cookie[] cookies,
                                    String cookieName,
                                    String defaultValue) throws IOException {
    int length = cookies.length;
    System.out.println(length);
    try{
    for(int i=0; i<length; i++) {
        Cookie cookie = cookies[i];
        if (cookieName.equals(cookie.getName())) {
            System.out.println(cookies.length);
            return(cookie.getValue());
        } else {
            return defaultValue;
        }
    } } catch (NullPointerException e){
        e.printStackTrace();
        HttpServletResponse res = null;
        res.sendRedirect("../Login.jsp");
    }
    return(defaultValue);
}

}
这是我的web xml文件:

<filter>
    <filter-name>SecurityFilter</filter-name>
    <filter-class>filters.newFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SecurityFilter</filter-name>
    <url-pattern>/add/addAuthor.jsp</url-pattern>
    <url-pattern>/add/addAuthor</url-pattern>
    <url-pattern>/add/addConference.jsp</url-pattern>
    <url-pattern>/add/addConference</url-pattern>
    <url-pattern>/add/addJournal.jsp</url-pattern>
    <url-pattern>/add/addJournal</url-pattern>
    <url-pattern>/add/addWorkshop.jsp</url-pattern>
    <url-pattern>/add/addWorkshop</url-pattern>
    <url-pattern>/add/index.jsp</url-pattern>
</filter-mapping>

<filter>
    <filter-name>AdminFilter</filter-name>
    <filter-class>filters.adminFilter</filter-class>
</filter>
<!--  <filter-mapping>
    <filter-name>AdminFilter</filter-name>
    <url-pattern>/add/addAuthor.jsp</url-pattern>
    <url-pattern>/add/addAuthor</url-pattern>
    <url-pattern>/add/addConference.jsp</url-pattern>
    <url-pattern>/add/addConference</url-pattern>
    <url-pattern>/add/addJournal.jsp</url-pattern>
    <url-pattern>/add/addJournal</url-pattern>
    <url-pattern>/add/addWorkshop.jsp</url-pattern>
    <url-pattern>/add/addWorkshop</url-pattern>
    <url-pattern>/add/index.jsp</url-pattern>
    <url-pattern>/add/addConfJour.jsp</url-pattern>
    <url-pattern>/add/addConfJourn</url-pattern>
    <url-pattern>/add/addUser.jsp</url-pattern>
    <url-pattern>/add/addUser</url-pattern>
    <url-pattern>/add/addTag.jsp</url-pattern>
    <url-pattern>/add/addTag</url-pattern>
    <url-pattern>/add/indexAdmin.jsp</url-pattern>
</filter-mapping>-->

<filter-mapping>
    <filter-name>AdminFilter</filter-name>
    <url-pattern>/add/*</url-pattern>
</filter-mapping>

你确定你真的想实现你自己的访问安全吗?servlet规范支持受保护的资源,因此您基本上可以做您正在做的事情。您可能仍然希望编写一个筛选器,将用户对象弹出到会话中

看一下这个关于使用容器身份验证保护对web资源的访问的链接

再看看你的代码,有一些东西闻起来不太好

Java命名约定所有类都应该以大写字符开头 成员变量被保留在包保护中-理想情况下,这些变量应该是私有的 这两个过滤器非常相似,但在抽象父类或实用程序类中不共享公共代码 正在为每个登录查找创建数据库连接-这是高效的-理想情况下,数据访问应该通过数据访问层,并且应该使用连接池,以便重新使用连接,并且您不会创建太多连接 关闭资源-不能保证数据库连接正确关闭。请看使用finally块关闭资源 异常处理-不应吞并异常-将它们包装在ServletException中并将其抛出 捕获NullPointerException这些不应该被捕获,通常是由小学生编写的代码错误引起的。
这是我的密码。我不明白为什么当我用一个非管理员帐户登录时,它还不起作用。我知道我的客户已经告诉我用这种方式登录。你有什么建议吗?两个过滤器的FilterMappings都指向同一个/add文件夹。所以这两个过滤器都将被调用。也许你只想让你的管理员资料通过管理员过滤器。谢谢你,这已经解决了。我现在明白了这是好事。