为什么我的 javascript 文件不能像 jsp 那样识别 servlet?

问题描述 投票:0回答:1

我有一个名为 like

的 servlet

@WebServlet("/UserServlet")
,当我在 JSP 上使用
action="UserServlet"
时,它可以识别它,但 JavaScript 文件不能。 文件路径信息: Servlet 位于
src/main/java/com.name.controller/UserServlet
。 JSP 位于
webapp/view/| JavaScript file lcoated at 
webapp/js/`

当我这样做时:

    fetch('/UserServlet', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: registrationDataJSON
    })
        .then(response => response.json())
        .then(data => {
            // handle success or error response
            if (data.status === 'success') {
                // redirect to home page or display success message
            } else {
                // display error message
                alert(data.message);
            }
        })
        .catch(error => {
            // handle network or server error
            console.error(error);
        });
    return true;
};

这重定向到

localhost:8080/UserServlet
而不是
localhost:8080/ProjectName/UserServlet
.

但是当我像这样提到 servlet 的完整路径时:

fetch('http://localhost:8080/projectname/UserServlet', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: registrationDataJSON
    }

然后它就可以工作了,难道我不能只使用 Servlet 名称而不是完整路径就可以让它工作吗?

javascript java jsp servlets fetch
1个回答
0
投票

由于您使用的是 Fetch API,因此它的第一个参数使用您必须自己构建的 URL 对象。

let base_url = 'http://localhost:8080/projectname';
fetch(base_url+'/UserServlet', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: registrationDataJSON
    }

如果您不想对基本 URL 进行硬编码,那么您可以从服务器或

Window
对象属性中获取它。
window.location.origin
可用于基本 URL。

© www.soinside.com 2019 - 2024. All rights reserved.