无法从servlet获取传递的数据

我正在编写一个与常规jsp-servlet交互工作正常的程序。 但是当我用ajasx提交相同的内容时,它并没有正常工作。 以下是我的代码。

JSP-Servlet(没有Ajax)

的index.jsp

     Insert title here   

调节器

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String nsme = request.getParameter("name1"); request.setAttribute("name", nsme); request.getRequestDispatcher("index1.jsp").forward(request, response); } 

index1.jsp

      Insert title here      

使用Ajax

的index.jsp

      Insert title here    

SampleJS.js

 $('#x').click(function() { $.ajax({ type : 'POST', url : 'Controller', success : function(data) { console.log(data) }, }); }); 

调节器

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String nsme = request.getParameter("name1"); request.setAttribute("name", nsme); request.getRequestDispatcher("index1.jsp").forward(request, response); } 

index1.jsp

      Insert title here      

这里当我使用第一种方法时,名称打印正确。 当我将它与AJAX一起使用时,令我惊讶的是,文本框中没有任何内容。

基本上,我们使用request.getRequestDispatcher("GetCaseData.jsp").forward(request, response); 去另一页。 在我的情况下,它的替代品是什么? 请让我知道我哪里出错了,我该如何解决这个问题。

在Ajax情况下,您不发送任何表单数据。 使用$.serialize序列化表单数据并将其发送到服务器:

 $('#x').click(function() { var formData = $("#f1").serialize(); $.ajax({ type : 'POST', url : 'Controller', data : formData, success : function(data) { console.log(data) }, }); }); 

在js文件中添加formData之后
检查浏览器控制台

您可以在控制台中找到整个index1.jsp html内容,其中$ {name}替换为您输入的名称。
建议AJAX调用用于保持同一页面并更新页面内容,而不会在调用后刷新页面。
在使用AJAX的上述代码中,即使在AJAX调用完成之后,您也只在index.jsp中
您可以使用javascript window.location.href = <您的文件名>在AJAX调用后切换到其他页面(在您的情况下为index1.jsp )。 但是在您的情况下,页面切换到index1.jsp但作为新请求。 您可以在浏览器URL栏中观察到相同的内容。 在请求范围中存储名称attibute时。 您将看不到在index1.jsp的name字段中输入的值。