Search code examples
jqueryajaxjspservletsjava-ee-6

Call annotated HttpServlet from jsp with jquery


I try to impelemnt my first JavaEE project, but I allways get 404 error, when I try to call GET on my HttpServlet. I've read a lot of SO posts and tutorials, but I wasn't able to find any solution. Here is my index.jsp

    <%--
  Created by IntelliJ IDEA.
  User: molnard
  Date: 2017. 06. 13.
  Time: 10:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Learn Jsp</title>
    <script src="/lib/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#myspan").click(function () {
                $.ajax({
                    type: "GET",
                    url: "/FirstServlet",
                    success: function () {
                        window.alert("Success");
                    },
                });
            });
        });
    </script>
</head>
<body>
<%int age = 34;%>
<%String name = "Daniel"; %>
<%String numberOfProject = "first";%>
<span id="myspan">My name is <%=name%> and I'm <%=age%> years old. This is my <%=numberOfProject%> jsp project.</span>
</body>
</html>

And this is my Servlet generated by Intellijpackage servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by molnard on 2017. 06. 13..
 */
@WebServlet(name = "FirstServlet")
public class HttpServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

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

    }
}

I can see this error on browser consol:`

GET http://localhost:8080/FirstServlet 404 ()

This is my project structure

enter image description here


Solution

  • Your @WebServlet(name = "FirstServlet") annotation hasn't url pattern.

    You can try adding url pattern :

    @WebServlet(name = "MyOwnServlet", urlPatterns = "/FirstServlet")
    

    Or just like this :

    @WebServlet("/FirstServlet")
    

    Finally, you can access wherever you want using contextPath:

    ${pageContext.request.contextPath}/FirstServlet