einstein
einstein

Reputation: 13850

Servlet mapping for ajax call parameters

I have ajax calls that have the url http://localhost:80/Push/GetContacts?id=23 and the following servlet mapping:

<servlet-mapping>
      <servlet-name>Test</servlet-name>
      <url-pattern>/GetContacts*</url-pattern>
</servlet-mapping>

The servlet does not get invoked on ajax calls. It returns a HTTP 404 not found response. What is the right URL pattern for my ajax calls?

Here is the ajax call that is not working because of the servlet.

jQuery.getJSON('http://localhost:8080/Push/GetContacts&callback=?', function(data) {
     alert(data.data);
});

The servlet:

public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException{
        try{
            resp.setContentType("text/html");
            PrintWriter out = resp.getWriter();
            out.write("{data: helloworld}");
            out.close();

        }
        catch(Exception e){
            e.printStackTrace();
        }

Upvotes: 1

Views: 2763

Answers (1)

J&#246;rn Horstmann
J&#246;rn Horstmann

Reputation: 34014

The url pattern needs to be just /GetContacts without the star. The parameters are not part of the servlet mapping and are ignored when finding the correct servlet. If you wanted to support an URL like /GetContacts/23 you could use a servlet mapping for /GetContacts/* and retrieve the id using request.getPathInfo.

Edit: as BalusC just noticed, the url in your ajax call is incorrect. The parameter callback should be separated by a question mark, not an ampersand: GetContacts?callback=...

Also, {data: helloworld} is invalid according to the json spec, both data and helloworld should be enclosed in quotes. But that is also independent from the 404 problem.

Upvotes: 3

Related Questions