简体   繁体   中英

jQuery - AJAX call of Servlet

I'm building a web app for store scientific publications. I've used MySQL, JSP, jQuery and JAVA.

I have a form inside a JSP page, like this:

<form method="get">
    <input type="text" id="code">
    <button onclick="request()">Search</button>
</form>

The function request() is:

function request() {
    var code = $('#code').val();
    var data='code='+code;
    $.ajax({
          url: "Servlet",
          type: "GET",
          data: data,
          success: function(){
              alert("success");
          },
          error:function(){
              alert("failure");
          }   
        }); 
};

The Servlet do some stuff and then save the resultset of query in the request object and forward the result on the index like this

request.setAttribute("result", resultSet);
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);

The index.jsp contains:

 <%  if(request.getAttribute("result")!=null){ %>
        <jsp:include page="table.jsp" />
  <%}%>

check if the result set is already filled, then include table.jsp, the page scan the resultset and put the values in a table.

This code doesn't work, someone can help me? 1- The query runs correctly 2- jQuery is called correctly

but the

if(request.getAttribute("result"))

is always null.

Try to let your Servlet extends HttpServlet ,and try it as below:

public class TestServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;


    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request,response);
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        request.setAttribute("result", "value");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM