JSP 报错:ReferenceError: $ is not defined

When running the SpringMVC project, the JSP code reports an error:

ReferenceError: $ is not defined

The relevant JSP code is as follows:

...
<script src="js/jquery-3.3.1.min.js"></script>
<script>
    $("#btn").on("click", function () {
        $.ajax({
            type: "post",
            url: "register",
            data: $("form").serialize(),
            success: function (data) {
                console.log(data);
                alert("注册成功");
            },
            error: function (xhr, type, errorThrown) {
                console.log("xhr:" + xhr + " type:" + type + " errorThrown:" + errorThrown);
            }
        });
    });
</script>
...

The configuration of web.xml file is as follows:

<servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

This is because the mapping path configuration DispatcherServlet is /when will overwrite the default configuration tomcat, so need to be configured in SpringMVC file, the release of static resources:

...
<!-- 配置放行静态资源 -->
<mvc:default-servlet-handler/>
...

In this way, after a static resource request is issued, the DispatcherServlet will map and match the request. If the match is unsuccessful, it will be forwarded to the default of tomcat for processing.

If you do not use the SpringMVC framework, these static resource requests will be processed by the tomcat default.

Tomcat's default configuration is that when the request path is matched with all other servlets or not matched, the request will be sent to the default and processed by the DefaultServlet; generally requested static resources, invalid paths, etc. will be processed through the DefaultServlet.

Want to know more, welcome to follow my WeChat public account: Renda_Zhang

Guess you like

Origin blog.csdn.net/qq_40286307/article/details/108890857
Recommended