您的位置:首页 > 编程语言 > Java开发

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

2012-04-10 16:38 375 查看
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();
}

}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐