Struts 配置文件 struts.xml 扩展,自定义

1.XML配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
    "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="globalstruts" extends="json-default">
		<!-- action 自定义 result -->
		<result-types>
            <result-type name="sslStream" class="com.valley.securitymail.action.SSLStreamResult"/>
        </result-types>
	
		<interceptors>
		<interceptor name="timeOut" class="com.valley.securitymail.interceptor.TimeOutInterceptor"/>
		<interceptor name="throwException" class="com.valley.securitymail.interceptor.ExceptionInterceptor"/>
		<interceptor-stack name="timeOuts">
			<interceptor-ref name="defaultStack">   <!-- 默认拦截器   -->
				 <param name="validation.includeMethods">sendMail,saveDraft</param>
			</interceptor-ref>
			<interceptor-ref name="throwException"/>  <!-- 异常拦截器   -->
			<interceptor-ref name="timeOut"/> <!-- 超时拦截器   -->
			<interceptor-ref name="fileUpload">  <!-- 文件上传拦截器   -->
			   <param name="maximumSize">10737418240</param>
			</interceptor-ref>
		</interceptor-stack>
	</interceptors>
	
	<default-interceptor-ref name="timeOuts"/>
	<default-action-ref name="defaultAction"/>
	
	<global-results>
		<result name="timeout" type="redirect">Index.action?istimeout=1</result>
		<result name="input" >/WEB-INF/Jsps/msg.jsp</result>
		<result name="exceptionerror" >/WEB-INF/Jsps/exception_error.jsp</result>
	</global-results>
	
	<!-- 全局 异常 -->
	<global-exception-mappings>
		<exception-mapping result="exceptionerror" 
			exception="com.valley.securitymail.util.BaseException"></exception-mapping>
	</global-exception-mappings>
	
	<!-- 全局默认  action -->
	<action name="defaultAction">
			<result type="redirectAction">
			<param name="actionName">Index</param>
			</result>
	</action>
	</package>
</struts>


2.用到的类

            1. com.valley.securitymail.action.SSLStreamResult

package com.valley.securitymail.action;

import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.StreamResult;
import org.apache.struts2.dispatcher.StrutsResultSupport;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
/**
 * 
* 类 功 能:处理SSL加密后文件下载问题
* 
* 完成日期:2012-2-24
*
 */
public class SSLStreamResult extends StrutsResultSupport {

		private static final long serialVersionUID = 7526185492537885181L;

		protected static final Logger LOG = LoggerFactory.getLogger(StreamResult.class);

	    public static final String DEFAULT_PARAM = "inputName";

	    protected String contentType = "text/plain";
	    protected String contentLength;
	    protected String contentDisposition = "inline";
	    protected String inputName = "inputStream";
	    protected InputStream inputStream;
	    protected int bufferSize = 1024;
	    protected boolean allowCaching = true;

	    public SSLStreamResult() {
	        super();
	    }

	    public SSLStreamResult(InputStream in) {
	        this.inputStream = in;
	    }

	    /**
	     * @see org.apache.struts2.dispatcher.StrutsResultSupport#doExecute(java.lang.String, com.opensymphony.xwork2.ActionInvocation)
	     */
	    protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {

	        // Override any parameters using values on the stack
	        resolveParamsFromStack(invocation.getStack());

	        OutputStream oOutput = null;

	        try {
	            if (inputStream == null) {
	                // Find the inputstream from the invocation variable stack
	                inputStream = (InputStream) invocation.getStack().findValue(conditionalParse(inputName, invocation));
	            }

	            if (inputStream == null) {
	                String msg = ("Can not find a java.io.InputStream with the name [" + inputName + "] in the invocation stack. " +
	                    "Check the <param name=\"inputName\"> tag specified for this action.");
	                LOG.error(msg);
	                throw new IllegalArgumentException(msg);
	            }

	            // Find the Response in context
	            HttpServletResponse oResponse = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);

	            // Set the content type
	            oResponse.setContentType(conditionalParse(contentType, invocation));

	            // Set the content length
	            if (contentLength != null) {
	                String _contentLength = conditionalParse(contentLength, invocation);
	                int _contentLengthAsInt = -1;
	                try {
	                    _contentLengthAsInt = Integer.parseInt(_contentLength);
	                    if (_contentLengthAsInt >= 0) {
	                        oResponse.setContentLength(_contentLengthAsInt);
	                    }
	                }
	                catch(NumberFormatException e) {
	                    LOG.warn("failed to recongnize "+_contentLength+" as a number, contentLength header will not be set", e);
	                }
	            }

	            // Set the content-disposition
	            if (contentDisposition != null) {
	                oResponse.addHeader("Content-Disposition", conditionalParse(contentDisposition, invocation));
	            }

	            // Set the cache control headers if neccessary
	         /*   if (!allowCaching) {
	                oResponse.addHeader("Pragma", "no-cache");
	                oResponse.addHeader("Cache-Control", "no-cache");
	            }*/
	         //   if(SecurityConfig.IS_ACTIVATE_SECURITY){   //解决SSL加密后 文件下载问题
	              oResponse.setHeader("Pragma", "public");
		          oResponse.setHeader("Cache-Control", "public");
	            //}
	            // Get the outputstream
	            oOutput = oResponse.getOutputStream();

	            if (LOG.isDebugEnabled()) {
	                LOG.debug("Streaming result [" + inputName + "] type=[" + contentType + "] length=[" + contentLength +
	                    "] content-disposition=[" + contentDisposition + "]");
	            }

	            // Copy input to output
	            LOG.debug("Streaming to output buffer +++ START +++");
	            byte[] oBuff = new byte[bufferSize];
	            int iSize;
	            while (-1 != (iSize = inputStream.read(oBuff))) {
	                oOutput.write(oBuff, 0, iSize);
	            }
	            LOG.debug("Streaming to output buffer +++ END +++");

	            // Flush
	            oOutput.flush();
	        }
	        finally {
	            if (inputStream != null) inputStream.close();
	            if (oOutput != null) oOutput.close();
	        }
	    }

	     /**
	     * @return Returns the whether or not the client should be requested to allow caching of the data stream.
	     */
	    public boolean getAllowCaching() {
	        return allowCaching;
	    }

	    /**
	     * Set allowCaching to <tt>false</tt> to indicate that the client should be requested not to cache the data stream.
	     * This is set to <tt>false</tt> by default
	     *
	     * @param allowCaching Enable caching.
	     */
	    public void setAllowCaching(boolean allowCaching) {
	        this.allowCaching = allowCaching;
	    }


	    /**
	     * @return Returns the bufferSize.
	     */
	    public int getBufferSize() {
	        return (bufferSize);
	    }

	    /**
	     * @param bufferSize The bufferSize to set.
	     */
	    public void setBufferSize(int bufferSize) {
	        this.bufferSize = bufferSize;
	    }

	    /**
	     * @return Returns the contentType.
	     */
	    public String getContentType() {
	        return (contentType);
	    }

	    /**
	     * @param contentType The contentType to set.
	     */
	    public void setContentType(String contentType) {
	        this.contentType = contentType;
	    }

	    /**
	     * @return Returns the contentLength.
	     */
	    public String getContentLength() {
	        return contentLength;
	    }

	    /**
	     * @param contentLength The contentLength to set.
	     */
	    public void setContentLength(String contentLength) {
	        this.contentLength = contentLength;
	    }

	    /**
	     * @return Returns the Content-disposition header value.
	     */
	    public String getContentDisposition() {
	        return contentDisposition;
	    }

	    /**
	     * @param contentDisposition the Content-disposition header value to use.
	     */
	    public void setContentDisposition(String contentDisposition) {
	        this.contentDisposition = contentDisposition;
	    }

	    /**
	     * @return Returns the inputName.
	     */
	    public String getInputName() {
	        return (inputName);
	    }

	    /**
	     * @param inputName The inputName to set.
	     */
	    public void setInputName(String inputName) {
	        this.inputName = inputName;
	    }
	    /**
	     * Tries to lookup the parameters on the stack.  Will override any existing parameters
	     *
	     * @param stack The current value stack
	     */
	    protected void resolveParamsFromStack(ValueStack stack) {
	        String disposition = stack.findString("contentDisposition");
	        if (disposition != null) {
	            setContentDisposition(disposition);
	        }

	        String contentType = stack.findString("contentType");
	        if (contentType != null) {
	            setContentType(contentType);
	        }

	        String inputName = stack.findString("inputName");
	        if (inputName != null) {
	            setInputName(inputName);
	        }

	        String contentLength = stack.findString("contentLength");
	        if (contentLength != null) {
	            setContentLength(contentLength);
	        }

	        Integer bufferSize = (Integer) stack.findValue("bufferSize", Integer.class);
	        if (bufferSize != null) {
	            setBufferSize(bufferSize.intValue());
	        }
	    }


}


2.com.valley.securitymail.interceptor.TimeOutInterceptor

package com.valley.securitymail.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.valley.securitymail.action.IndexAction;
import com.valley.securitymail.action.MailReceiveAction;
import com.valley.securitymail.action.MailSearchAction;
import com.valley.securitymail.action.MailShowImageAction;
import com.valley.securitymail.action.UserLoginAction;
import com.valley.securitymail.bean.JamesUser;

/**
 *类 功 能:处理Session超时,禁用Jsp页面缓存
* 
* 完成日期:2012-2-8
*
 */
@SuppressWarnings("serial")
public class TimeOutInterceptor extends AbstractInterceptor {

	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		JamesUser user = (JamesUser) ai.getInvocationContext().getSession().get("user");
		Object store = ai.getInvocationContext().getSession().get("store");
		Object sessionMail = ai.getInvocationContext().getSession().get("session");
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		Object action = ai.getAction(); 
		String returninfo = "";
		if((action instanceof UserLoginAction)||(action instanceof IndexAction)||(action instanceof MailShowImageAction)){
			//排除登录前、时的 拦截
			returninfo = ai.invoke();
			return returninfo;
		}
		else if(user==null||store==null||sessionMail==null){
		//	System.out.println("连接超时");
			return "timeout"; 
		}else{
	
			returninfo = ai.invoke();
			//拦截 之后   禁用页面缓存
			if (request.getProtocol().compareTo("HTTP/1.0")==0)
				response.setHeader("Pragma","no-cache");
			if (request.getProtocol().compareTo("HTTP/1.1")==0)
				response.setHeader("Cache-Control","no-cache");
			response.setDateHeader("Expires",0);
			return returninfo;
		}
	}

}


3.com.valley.securitymail.interceptor.ExceptionInterceptor

package com.valley.securitymail.interceptor;

import java.io.IOException;
import java.sql.SQLException;

import javax.mail.MessagingException;

import org.springframework.dao.DataAccessException;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.valley.securitymail.util.BaseException;

@SuppressWarnings("serial")
public class ExceptionInterceptor extends AbstractInterceptor {
	private String result ;
	@Override
	public String intercept(ActionInvocation ai){
		result = "exceptionerror";
		try{  
			 result = ai.invoke();
			}catch(DataAccessException e ){
				e.printStackTrace();
				throw new BaseException("数据库操作失败!");  
			}catch(NullPointerException e){  
				e.printStackTrace();
				throw new BaseException("调用了未经初始化的对象或者是不存在的对象!");  
			}catch(IOException e){  
				e.printStackTrace();
				throw new BaseException("IO异常!");  
			}catch(ClassNotFoundException e){
				e.printStackTrace();
				throw new BaseException("指定的类不存在!");  
			}catch(ArithmeticException e){  
				e.printStackTrace();
				throw new BaseException("数学运算异常!");  
			}catch(ArrayIndexOutOfBoundsException e){  
				e.printStackTrace();
				throw new BaseException("数组下标越界!");  
			}catch(IllegalArgumentException e){
				e.printStackTrace();
				throw new BaseException("方法的参数错误!");  
			}catch(ClassCastException e){  
				e.printStackTrace();
				throw new BaseException("类型强制转换错误!");  
			}catch(SecurityException e){  
				e.printStackTrace();
				throw new BaseException("违背安全原则异常!");  
			}catch(SQLException e){  
				e.printStackTrace();
				throw new BaseException("操作数据库异常!");  
			}catch(NoSuchMethodError e){  
				e.printStackTrace();
				throw new BaseException("方法未找到异常!");  
			}catch(InternalError e){  
				e.printStackTrace();
				throw new BaseException("Java虚拟机发生了内部错误");  
			}catch (MessagingException e) {
				e.printStackTrace();
				//throw new BaseException("邮件服务器验证错误!"); 
			}catch(Exception e){  
				e.printStackTrace();
				throw new BaseException("程序内部错误,操作失败!");  
			}  
		return result;	
		}

}

 

4.com.valley.securitymail.util.BaseException

 

package com.valley.securitymail.util;
/**
 * 类 功 能:异常处理
* 完成日期:2012-2-8
*
 */
public class BaseException extends RuntimeException {
	private static final long serialVersionUID = -9172497819545501914L;
	public BaseException(String msg) {  
	         super(createErrMsg(msg));  
	     }  
	public BaseException(Throwable throwable){  
	         super(throwable);  
	     } 
    public BaseException(Throwable throwable, String msg){  
	         super(throwable);  
	     }  
	private static String createErrMsg(String msgBody){  
	 String prefixStr = "抱歉,";  
	 String suffixStr = ".  请稍后再试或与管理员联系!";  
	 StringBuffer errMsg = new StringBuffer("");  
	 errMsg.append(prefixStr) 
	 		.append(msgBody) 
	 		.append(suffixStr);  
	 return errMsg.toString();  
	 }  

}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值