使用POST請求實現頁面的跳轉


項目情景:

當用戶選擇幾個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 必須不一樣 ,否則會發生無限循環錯誤.

 

參考: http://suryakand-shinde.blogspot.com/2016/07/aem-form-submission-handling-post.html

forward()和sendRedirect()的區別: https://examples.javacodegeeks.com/enterprise-java/servlet/java-servlet-sendredirect-example/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM