在JSP Servlet中处理Ajax请求

时间:2017-05-28 02:06:42

标签: java ajax jsp servlets

我正在使用JSP和Ajax的示例来抛出名称和总和,但是我没有看到带有结果的窗口。这些是我的文件

我找不到错误,或者他们认为的错误,或者我可以解决它的问题?

的index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%>

    <!DOCTYPE html>
    <html>
<head>
<title>Demo Ajax</title>

<link href="/resources/css/miPrimerCSS.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="resources/js/jquery.js"></script>
<script type="text/javascript">



  $(document).ready(function(){
     $('#unHola').click(function(){
         var nombreCompleto = $('#nombreCompleto').val();
         $.ajax({
             type:'POST',
             data: {
                 nombreCompleto : nombreCompleto,
                 action: 'demo1'
             },
             url: 'AjaxController',
             success: function(result){
                 $('#resultado1').html(result);
             }

         });
     });

     $('#unaSuma').click(function(){
         var numero1 = $('#numero1').val();
         var numero2 = $('#numero2').val();
         $.ajax({
             type:'POST',
             data: {
                 numero1 : numero1,
                 numero2 : numero2,  
                 action: 'demo2'
             },
             url:'AjaxController',
             success : function(result){
                 $('#resultado2').html(result);
             }

         });
     }); 



  }); // $(document).ready(function()

</script>
</head>
<!-- <span id="titulo">Un Saludo</span>
<p style="font-size: 20px">Un Hola<p>

-->
 <body>

     <fieldset>
        <h1>Un Hola</h1>
           <form>
              Nombre <input type="text" id="nombreCompleto"><br>
              <input type="button" value="Hola" id="unHola"><br> 
              <span id="resultado1"></span>
           </form>
     </fieldset>


     <fieldset>
          <h2>Una Suma</h2>
             <form>
                Numero 1 <input type="text" id="numero1"><br>
                Numero 2 <input type="text" id="numero2"><br> 
                Resultado <span id=resultado2></span><br>
                <input type="button" value="Suma" id="unaSuma">


             </form>
    </fieldset>



  </body>

</html>

AjaxController.java

package controladores;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AjaxController
 */
@WebServlet("/AjaxController")
public class AjaxController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }



    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain ");

        PrintWriter out =  response.getWriter();
        String action = request.getParameter("action");

        if(action.equals("demo1")){
            String nombreCompleto = request.getParameter("nombreCompleto");
            out.println("Hola " + nombreCompleto);
        }
        else if (action.equals("demo2")){
            int a = Integer.parseInt(request.getParameter("numero1"));
            int b = Integer.parseInt(request.getParameter("numero2"));
            out.println(a + b);
        }



    }

}

示例应该是如此

enter image description here

1 个答案:

答案 0 :(得分:1)

我在我的上下文中重新运行代码,并在以下修复后按预期运行。试试看:

  • 您的 JQuery 可能无法正确加载。尝试确保此导入网址有效并运行<script type="text/javascript" src="resources/js/jquery.js"></script>
  • 考虑使用一些 jstl taglib 支持加载上下文相关资源,例如<script src="<c:url value="/resources/js/jquery.min.js" />"></script>

  • <script></script>放在身体的末端。实际上,在正文末尾加载JS文件是一个好习惯,因此它不会阻止页面加载。

更多提示:

  • 除非你真的计划任何自定义的东西,否则你不需要在Servlet中声明构造函数

  • 如果您不使用doGet(),请不要将其保留在Servlet中。