我有一个名为 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 名称而不是完整路径就可以让它工作吗?
由于您使用的是 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。