ajax ajax调用servlet并重定向到jsp

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16870018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 11:02:26  来源:igfitidea点击:

ajax call to servlet and redirect to jsp

ajaxjspservlets

提问by vagga ravi

Here in the below code i want to call a servlet through ajax and then i redirect the data from servlet to jsp.ajax call to servlet is working fine but the problem is redirecting to the jsp page is not displayed in the browser and the same jsp page is displayed when i used with javascript code without ajax.

在下面的代码中,我想通过 ajax 调用一个 servlet,然后我将数据从 servlet 重定向到 jsp.ajax 对 servlet 的调用工作正常,但问题是重定向到 jsp 页面未显示在浏览器中,并且相同的 jsp当我在没有 ajax 的情况下使用 javascript 代码时显示页面。

javascript ajax code in the jspfile:

jspfile 中的 javascript ajax 代码:

function generate(){
...
...
 var url="RedirectServlet";
 var ajax=new AJAXInteraction(url,"RedirectServlet");
 var param    ="FD="+FD+"&TD="+TD+"&actionid="+status+"&usercode="+usercode+"&action=reports"+"";
 ajax.send(param);

....
 }
 function AJAXInteraction(url, actionType) {
     this.url = url;

     var req = init();
   var actionRequested = actionType;
     req.onreadystatechange = processRequest;      
    function init() {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
     }

     function processRequest () {
        if (req.readyState == 4) {
            if (req.status == 200) {                                
                if(actionRequested=="TestDelegation") {                     
                    PostProcess1(req.responseXML);
                }

            }
        }
     }
     this.send = function(param) {
        req.open("POST", url, true);

        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        req.send(param);


     }
}//end of AJAX Interaction object.

Servlet code:

服务端代码:

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
        {
    System.out.println("calling doPost() ");

    response.setContentType("text/html;charset=WINDOWS-1256");
    String action=request.getParameter("action");
    System.out.println(action);

    if(action.equals("reports")){
        System.out.println("inside reports");



        //Getting values from Reports_arb.jsp
        String Fromdate=request.getParameter("FD");
        String Todate=request.getParameter("TD");
        String status=request.getParameter("actionid");
        String usercode=request.getParameter("usercode");

        //placing given values in a session 


        request.setAttribute("FD", Fromdate);
        request.setAttribute("TD", Todate);
        request.setAttribute("actionid", status);
        request.setAttribute("usercode", usercode);


        //Redirecting to showReport_arb.jsp
        //response.sendRedirect("showReport_arb.jsp");

          ServletContext sc = getServletContext();
            sc.getRequestDispatcher("/sample.jsp").forward(request, response); 

回答by Rajan Twanabashu

You need to understand the fact that when you send http request from ajax, it means that you are sending the request in separate thread and not in the main thread (the page itself from where you are sending the request). So redirection at the servlet will not reflect at the client end. In order to achieve this, send back the URL to which you want to redirect as a response to request and on success method of ajax simply use java script window.location(URL);

您需要了解这样一个事实,即当您从 ajax 发送 http 请求时,这意味着您是在单独的线程中发送请求,而不是在主线程(发送请求的页面本身)中发送请求。因此 servlet 的重定向不会反映在客户端。为了实现这一点,发送回您想要重定向到的 URL 作为对请求的响应,并且在 ajax 的成功方法中只需使用 java 脚本 window.location(URL);

At servlet

在 servlet

JSONObject jobj = new JSONObject()
String urlToRedirect = "test.jsp";
jobj.put("url",urlStr);
response.getWriter().write(jobj.toString());

At client end

在客户端

$.ajax({
                url: 'servletName',
                data: {
                    userID: selectedID
                },
                type: 'post',
                success: function(data){
                  window.location = data.url;
                } 

            });

回答by MaheshVarma

Instead of creating the requestand responseobject, use jquery Ajax. It is very simple to use.

而不是创建requestresponse对象,使用jquery Ajax。使用起来非常简单。

 /* Send the data using post and put the results in a div */

 $.ajax({
  url: "/YourServlet",
  type: "post",
  data: values,
  success: function(){
      alert("success");
       $("#result").html('submitted successfully');
  },
  error:function(){
      alert("failure");
      $("#result").html('there is error while submit');
  }   
});