java - 如何从 ajax post 重定向到 servlet 到 jsp?

标签 java jquery eclipse jsp servlets

我正在为我们的系统进行登录,index.html 有这个脚本,

<script>
    $('#navbar').load('navbar.html');
    $('#errorMessage').hide();
    $("#loginBtn").click(function() { 
         $.post('http://localhost:8080/NewDesignV1/login.action',
            {
                username : $("#username").val(),
                password : $("#password").val()

            }
            ,'html');
    });
</script>

帖子位置是一个servlet,我需要转到这个servlet,以便我可以从index.html获取数据,对其进行操作并将其重定向到JSP页面。

我的问题是,我可以从ajax post获取数据,但当我使用时它不会重定向到JSP页面

request.setAttribute("key", value);
request.getRequestDispatcher("studentprofile.jsp").forward(request, response);

最佳答案

原因是你通过 $.post 调用它,所以它是一个 ajax 方法, 事实上 request.getRequestDispatcher("studentprofile.jsp").forward(request, response); 正在工作,你可以得到它

$("#loginBtn").click(function() { 
     $.post('http://localhost:8080/NewDesignV1/login.action',
        {
            username : $("#username").val(),
            password : $("#password").val()

        },
        function(data){
           console.log(data);//you can get the redirect jsp context
        },
        ,'html');
});

为了让studentprofile.jsp显示,需要避免使用$.post,可以创建一个表单,然后提交表单:

$("#loginBtn").click(function() { 
    var form = document.createElement("form");
    document.body.appendChild(form);
    $(form).append("<input type='hidden' name='username' value='"+$("#username").val()+"'>");
    $(form).append("<input type='hidden' name='password' value='"+$("#password").val()+"'>");
    form.action="http://localhost:8080/NewDesignV1/login.action";
    form.method="post";
    form.submit();
    $(form).remove();
});

关于java - 如何从 ajax post 重定向到 servlet 到 jsp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50013364/

相关文章:

java - 验证期间Struts2超时

javascript - 登录模块适用于除 Chrome 之外的任何地方

javascript - 在移动设备上使用 Chrome 浏览器强制视频自动播放

java - 如何更改 Eclipse 默认类路径

java - Eclipse E4 : Awful Eclipse/OSGI core NullPointerException (etc. )在启动时终止应用程序

Android(eclipse)PNG透明度显示为黑色(附图片示例)

java - 如何在 java/j2ee 中以编程方式为新闻网站生成 RSS?

java - OkHttp - 获取失败的响应正文

jquery - 避免 jQuery 和 jQuery 扩展中的冲突!

java - 从 xml 创建自定义 View