使用jquery从jsp调用带注释的HttpServlet

时间:2017-06-13 08:43:35

标签: jquery ajax jsp servlets java-ee-6

我尝试阻止我的第一个JavaEE项目,但是当我尝试在我的HttpServlet上调用GET时,我总是得到404错误。我已经阅读了很多SO帖子和教程,但我找不到任何解决方案。 这是我的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>

这是我的Intellijpackage servlet生成的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 {

    }
}

我可以在浏览器consol上看到这个错误:`

  

获取http://localhost:8080/FirstServlet 404()

这是我的项目结构

enter image description here

1 个答案:

答案 0 :(得分:0)

您的@WebServlet(name = "FirstServlet")注释没有网址格式。

您可以尝试添加网址格式:

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

或者就像这样:

@WebServlet("/FirstServlet")

最后,您可以使用contextPath访问任何位置:

${pageContext.request.contextPath}/FirstServlet