论坛首页 入门技术论坛

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

浏览 8192 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-03-24  

用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

   发表时间:2009-07-28  
这个主要用途是什么?
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics