Apache Struts 1:如何为AJAX请求返回经处理的JSP页面作为text/html
在Apache Struts 1中通过Action返回JSP渲染后的HTML内容(用于AJAX)
你可以利用Servlet的RequestDispatcher.include()方法,把JSP的渲染结果捕获到内存输出流里,再将这个字符串返回给AJAX请求,完全不需要触发Struts的转发或重定向。核心逻辑是让JSP把内容输出到你自己控制的StringWriter,而非直接输出到响应的输出流。
完整实现代码
public class HelloWorldAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // 1. 获取搜索关键词并查询结果 String searchTerms = request.getParameter("searchTerms"); // 假设请求参数名为searchTerms TabularDataForm searchResult = DataFactory.getSearchResult(searchTerms); // 2. 将结果存入request域(优先用request,避免会话冗余) request.setAttribute("searchResult", searchResult); // 3. 捕获JSP渲染后的HTML内容 StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); // 指定要渲染的JSP路径(根据你的项目结构调整,比如/WEB-INF/jsp/search-result.jsp) RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsp/search-result.jsp"); // 调用include,让JSP把内容输出到我们自定义的PrintWriter dispatcher.include(request, new HttpServletResponseWrapper(response) { @Override public PrintWriter getWriter() { return printWriter; } @Override public ServletOutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException("请使用getWriter()"); } }); // 4. 返回渲染后的HTML给AJAX请求 response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(stringWriter.toString()); out.flush(); return null; // 告诉Struts不要执行任何转发/重定向 } }
配套的JSP示例(search-result.jsp)
只需要编写表格的核心代码,不要包含<html>、<body>等全局标签,避免插入页面时破坏原有结构:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <table class="search-result-table"> <thead> <tr> <th>ID</th> <th>名称</th> <th>操作</th> </tr> </thead> <tbody> <c:forEach items="${searchResult.dataList}" var="item"> <tr> <td>${item.id}</td> <td>${item.name}</td> <td><a href="/details/${item.id}">查看详情</a></td> </tr> </c:forEach> </tbody> </table>
关键注意事项
- JSP路径要正确:如果JSP放在
WEB-INF目录下,直接使用/WEB-INF/jsp/xxx.jsp即可,Struts的RequestDispatcher可以正常访问。 - 优先使用Request域:AJAX是单次请求,把结果存入
request域足够,减少会话内存占用。 - 异常处理:实际项目中要给
dispatcher.include()添加try-catch块,捕获JSP渲染过程中可能出现的异常。 - 编码设置:必须指定
text/html类型和UTF-8编码,避免前端出现乱码。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

