浏览 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(); } } } }
@Results({ @Result(name = "strResult" , type=StringResult.class, value="testStr")})
在方法中先给testStr赋值,返回直接返回sttrResult就OK啦. testStr = "测试返回字符串123abc"; return "strResult";
因为我们的项目都是UTF-8编码的,所以没有做字符编码的处理.有兴趣的朋友自己处理吧. 可以查看org.apache.struts2.dispatcher.PlainTextResult 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-07-28
这个主要用途是什么?
|
|
返回顶楼 | |