项目情景:
当用户选择几个item之后,点击 查看 按钮之后, 页面跳转到展示items详情页面.
实现:
如果可以使用get请求, 直接在前端使用windows.loaction.href = "newUrl="xxx"&item=itemValue1&item=itemValue2"就行了
这样的问题是如果item比较多, 就有可能超出URL长度限制. 所以考虑用POST实现跳转.
server端:
@SlingServlet(resourceTypes = "/apps/xxx/components/pages/xxx-contentpage", extensions = "html", selectors = "selected", methods = {"GET", "POST"}, metatype = true )
public class MyServlet extends SlingAllMethodsServlet { @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { String newUrl= request.getParameter("newUrl"); RequestDispatcher dispatcher = request.getRequestDispatcher(newUrl); GetRequest getRequest = new GetRequest(request); dispatcher.forward(getRequest, response); } @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} /** Wrapper class to always return GET for AEM to process the request/response as GET. */ private static class GetRequest extends SlingHttpServletRequestWrapper { public GetRequest(SlingHttpServletRequest wrappedRequest) { super(wrappedRequest); } @Override public String getMethod() { return "GET"; } } }
如果直接forward POST request,会报错:
500 error - operations.ModifyOperation Exception during response processing
所以必须把request转换成GET request.
前端:
如果使用ajax提交请求,返回的将是新页面的html代码. 必须用form提交请求.
提示: form里面的action URL 与 servlet 的newUrl 必须不一样 ,否则会发生无限循环错误.
参考:
forward()和sendRedirect()的区别: