简体   繁体   中英

Servlet is not getting called by using jquery ajax in JSP?

I am working with JSP and Ajax for the first time. I am trying to get one column data from database and populate it in my drop down list in my JSP page using Ajax call. I don't want to refresh the page so that is the reason, I am making an Ajax call.

Here is my jsfiddle which has Process button and as soon as I click Process button, it will show an empty drop down list as of now. This is in my another test.jsp page.

I have a table as account and I need to make this select query from the jsp -

SELECT USERS FROM ACCOUNT;

As soon as I am clicking Process button, I need to execute above SQL query on my POSTGRESQL database using Ajax. And whatever users, I am getting back from the database, I need to populate those USERS in my drop down list as shown in my above jsfiddle.

Below is my servlet code which I am calling from a JSP page using Ajax.

@WebServlet("/someservlet/*")
public class SomeServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {

            System.out.println("Hello Test");
            // Step 1. Load the JDBC driver
            Class.forName("org.postgresql.Driver");

            // Step 2. Create a Connection object
            Connection con = DriverManager.getConnection(
                    "jdbc:postgresql://localhost/test","root", "root!");

            Statement s = con.createStatement();

            String sql ="SELECT USERS FROM ACCOUNT";
            ResultSet rs = s.executeQuery(sql);
            List<String> list = new ArrayList<String>();

            while (rs.next()) {
                list.add(rs.getString("email"));
            }
            String json = new Gson().toJson(list);
            response.getWriter().write(json);
            rs.close();
            s.close();
            con.close();
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        } catch (SQLException e2) {
            e2.printStackTrace();
        } catch (Exception e3) {
            e3.printStackTrace();
        }
    }
}

And below is my jquery ajax call from the above jsp page as shown in the jsfiddle from where I am calling the above servlet on the click of Process button -

<script type="text/javascript">
    $(document).ready(function() {
        $('.btn-primary').click(function() {
            alert("Hello");
            $.get('someservlet', function(responseJson) {
                alert(responseJson);
                var $ul = $('<ul>').appendTo($('#somediv'));
                $.each(responseJson, function(index, item) {
                    $('<li>').text(item).appendTo($ul);
                });
            });
        });
    });
</script>

Problem Statement:-

But somehow it is not working at all, meaning my servlet is not getting called at all from my JSP page using Ajax. My System.out is also not getting printed on the console as well from the servlet.

Also, I have one more servlet. This is the second servlet I have created. May be that is the reason?

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">

</web-app>

The problem is that this class it not a Servlet . It's just like a normal Java class.

It should extend HttpServlet

public class SomeServlet extends HttpServlet

The class on which this annotation @WebServlet is declared MUST extend HttpServlet .

Always try to use @Override annotation for overridden method to catch such type of errors at compile type itself.

jQuery's get(...) requires a valid URL. Here is what I tried with the code snippet you provided. This goes to the servlet. 1. provide the jQuery-version.js file

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" ></script>

2. The correct URL. The below URL will be called like this: http://localhost:8080/TestServlet/someservlet

$.get('someservlet', function(responseJson) {
alert(responseJson);
var $ul = $('<ul>').appendTo($('#somediv'));
$.each(responseJson, function(index, item) {
$('<li>').text(item).appendTo($ul);
});
}); 
  1. The servlet

     @WebServlet("/someservlet/*") public class TestServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) { System.out.println("Hello Test"); String json = "Hello from servlet"; try { response.getWriter().write(json); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

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