根据条件跳过Java过滤器

时间:2014-11-24 03:16:00

标签: java java-ee struts2 servlet-filters

我已查看How to skip a filter in the filter chain in java并按照解决方案进行操作,但这并没有帮助。

我的web.xml中有三个过滤器。 Struts过滤器,自定义过滤器和IAM代理过滤器按此顺序。我想根据某些条件跳过IAM过滤器。我没有控制IAM过滤器的外部代码和平。因此,当前端参数表示usertype是内部时我需要调用IAM代理过滤器,否则我需要跳过此过滤器。

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
id="WebApp_ID" 
version="2.5">
<display-name>App</display-name>
<!-- Struts2 Filter -->
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>*.action</url-pattern>
</filter-mapping>
 <!-- Custom App Filter for Handling Internal And External User-->
<filter>
   <filter-name>UserType</filter-name>
   <filter-class>com.App.web.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>UserType</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<!-- IAM Filter for Internal Users only-->
<filter>
   <filter-name>Agent</filter-name>
   <filter-class>com.sun.identity.agents.filter.AmAgentFilter</filter-class>
</filter>
<filter-mapping>
   <filter-name>Agent</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>   

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
    <listener-class>org.apache.tiles.web.startup.TilesListener</listener-class>
</listener>
<listener> 
    <listener-class>com.App.init.InitListener</listener-class>
</listener>
<context-param>
    <param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
    <param-value>/WEB-INF/tiles.xml</param-value>
</context-param>

<!-- Web Service -->
<servlet>
    <servlet-name>EventManagementWS</servlet-name>
    <servlet-class>com.App.eventmanagement.ws.EventManagementWS</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>EventManagementWS</servlet-name>
    <url-pattern>/EventManagementWS</url-pattern>
</servlet-mapping>
<resource-ref>
       <res-ref-name>url/ConfigProperty</res-ref-name>
       <res-type>java.net.URL</res-type>
       <res-auth>Container</res-auth>
       <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

我正在使用RequestDispatcher#forward(),但我的index.jsp页面输出中没有任何内容,只是一个空白页面。 css文件给出了404错误。当我使用Struts标签时,它给出了错误

Uncaught exception created in one of the service methods of the servlet /index.jsp in application App. Exception created: The Struts dispatcher cannot be found.  This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag.

所以我删除了S标签并使用了硬编码,但现在我在所有css中都遇到404错误,我试图将其包含在内。

我觉得前锋不能正常工作。

Java过滤代码:

package com.App.web.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.HttpSession;

import org.apache.commons.lang.StringUtils;

import com.App.constant.Constant;
import com.App.init.WIMSInitListener;
import com.App.log.WIMSMessageLogger;

public class LoginFilter implements Filter{

FilterConfig _filterConfig = null;
@Override
public void destroy(){
    // TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest request, ServletResponse response, 
       FilterChain filterChain) throws IOException, ServletException{
    // Check IAM is enabled
    if (InitListener.isIAMEnabled()){
        HttpSession session = httpRequest.getSession();
        String userType = (String) session.getAttribute(Constant.USER_TYPE);
        if(userType == null || "".equals(userType)){
            MessageLogger.putMessageLog("User type is null : First Request" + userType, getClass());
            userType = request.getParameter(Constant.USER_TYPE);
            session.setAttribute(Constant.USER_TYPE, userType);
            request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() + 
                    StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
                        .forward(request, response);

        }
        if("external".equals(userType)){
            MessageLogger.putMessageLog("External User" + userType, getClass());
            request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() + 
                    StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
                        .forward(request, response);

        }
        else if("internal".equals(userType)){
            MessageLogger.putMessageLog("Internal User" + userType, getClass());
            //IAM Filter com.sun.identity.agents.filter.AmAgentFilter
            filterChain.doFilter(request, response);
        }
   }
   //Its always External User
   else{
       MessageLogger.putMessageLog("User IAM Not Enabled", getClass());
       request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() + 
               StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()) )
                      .forward(request, response);

   }
}

@Override
public void init(FilterConfig filterConfig) throws ServletException{
    this._filterConfig = filterConfig;
} 
}

的index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01     Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>App</title>
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/common.css" />
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/style.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/default.css" />
<script type="text/javascript">
function selectUserType(){
var frm = document.forms["UserTypeForm"];
if(document.getElementById("userTypeInternal").checked){
    //frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
    frm.action='/App/loginAction.action?usertype=internal';
}
else{
    //frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
    frm.action='/App/loginAction.action?usertype=external';
}   
frm.target='_parent';
frm.submit();
}
function checkUserType(){   
//var userType = '<s:property value="#session.usertype" />';
var userType = '<%= session.getAttribute("usertype") %>';
if(userType == 'internal'){
    //frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
    frm.action='/App/loginAction.action?usertype=internal';
    frm.target='_parent';
    frm.submit();
}
else if(userType == 'external'){
    //frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
    frm.action='/App/loginAction.action?usertype=external';
    frm.target='_parent';
    frm.submit();
}
}
</script>
</head>
<body onload="javascript:checkUserType();">
<form method="POST" action="loginAction.action" name="UserTypeForm">
    <div id="display_option"
        style="DISPLAY: none; position: absolute; top: 40%; width: 100%;"
        align="center">
        <div class="rcorp-tbl">
            <div style="width: 340px;">
                <div style="border: 1px solid #6da6fe; padding: 5px;">
                    <table style="background-color: #f0f8ff;" cellspacing=2 border=0>
                        <tr>
                            <td class="t-cellsecnowrap">Select User type:</td>
                            <td>
                            <td class="t-cell">
                                <div id="wwgrp_systemType" class="wwgrp">
                                    <div id="wwctrl_systemType" class="wwctrl">
                                        <input type="radio" name="UserType" id="internal" value="internal" checked/>
                                            <label for="userTypeInternal">Internal User (Sydney Trains Users)</label>&nbsp; 
                                        <input type="radio" name="userType" id="external" value="external"/>
                                            <label for="userTypeExternal">External User</label>&nbsp;&nbsp;&nbsp;&nbsp;
                                        <input type="button" name="applyBtn" id="applyBtn" class="btn" value="Go" title="Go" onclick="javascript:selectUserType();"/>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

不要试图在LoginFilter中控制它,而是创建一个扩展com.sun.identity.agents.filter.AmAgentFilter的新类,并在web.xml中对其进行配置。你的课程看起来像这样:

public class CustomFilter extends AmAgentFilter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (InitListener.isIAMEnabled()) {
            HttpSession session = httpRequest.getSession();
            String userType = (String) session.getAttribute(Constant.USER_TYPE);
            if ("internal".equals(userType)) {
                super.doFilter(servletRequest, servletResponse, filterChain);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}

如果满足if-block中的条件,super.doFilter()调用将仅执行AmAgentFilter中的操作;否则,我们忽略该过滤器并转到链中的下一个过滤器。

您可以在AmAgentFilter的web.xml 而不是中配置此过滤器。