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

發佈了270 篇原創文章 · 獲贊 19 · 訪問量 34萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章