struts2直接返回字符串..终于弄好了!

用struts2一直很舒服.就是缺少一个方便的返回字符串的方法.今天终于耐着性子看了看.原来不是很难啊..集成个类就可以了..废话不说了.直接看代码吧..



/**

 * 扩展Struts2返回类型,直接返回String

 * 

 * @author Carmack Created on 2009-3-24 下午03:36:32

 */

public class StringResult extends ServletRedirectResult {

	/**

	 * @author Carmack Created on 2009-3-24 下午03:36:24

	 */

	private static final long serialVersionUID = -2800270132418148253L;

	

	private static final Logger LOG = LoggerFactory.getLogger(StringResult.class);

	

	public StringResult(){

		super();

	}

	

	public StringResult(String location){

		super(location);

	}

	

	

	public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {

		HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);

		HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(HTTP_REQUEST);

		

        response.setContentType("text/plain; charset=UTF-8");

        response.setHeader("Content-Disposition", "inline");



        PrintWriter writer = null;

        try {

        	writer = response.getWriter();

			writer.write(request.getAttribute(finalLocation).toString());

		} catch(NullPointerException e) {

			if(finalLocation.equals("")){

				LOG.warn("未指定value",e);

			}else{

				LOG.error("空",e);

			}

		} finally {

            if (writer != null) {

                writer.flush();

                writer.close();

            }

        }

	}

}



使用也很简单啦.

在Action上写

@Results({ @Result(name = "strResult" , type=StringResult.class, value="testStr")})

 

在方法中先给testStr赋值,返回直接返回sttrResult就OK啦.

testStr = "测试返回字符串123abc";
return "strResult";

 

因为我们的项目都是UTF-8编码的,所以没有做字符编码的处理.有兴趣的朋友自己处理吧.

可以查看org.apache.struts2.dispatcher.PlainTextResult

你可能感兴趣的:(struts2)