gpt4 book ai didi

Java、Spark、返回index.html

转载 作者:行者123 更新时间:2023-11-30 07:54:10 24 4
gpt4 key购买 nike

我正在尝试在服务器端使用 Spark 创建 SPA。这是我的 App.java:

package com.farot;
import java.util.HashMap;
import java.util.UUID;
import java.net.URL;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.charset.Charset;
import java.io.IOException;

import com.google.gson.Gson;

import static spark.Spark.*;

import com.farot.utils.Path;

import com.farot.controllers.UserController;
import com.farot.controllers.AccountController;
import com.farot.controllers.MapController;

public class App
{
private static Gson gson = new Gson();

private static String renderIndex() {
try {
URL url = App.class.getResource("index.html");
return new String(Files.readAllBytes(Paths.get(url.toURI())), Charset.defaultCharset());
} catch (IOException | URISyntaxException e) {
System.out.println(e.getMessage());
}
return null;
}

public static void main( String[] args )
{
staticFiles.location("/public");

before((req, res) -> {
String path = req.pathInfo();
if (path.endsWith("/"))
res.redirect(path.substring(0, path.length() - 1));
});

// Site pages
get("/", "text/html", (req, res) -> renderIndex());
get("/login", "text/html", (req, res) -> renderIndex());

post(Path.Web.api.Account.DEFAULT, (req, res) -> {
return AccountController.create(req, res);
}, gson::toJson);

}

}

Path.Web.api.Account.DEFAULT 的 POST 请求按预期工作,但/login 的请求返回 404。有什么问题吗?index.html 的路径是/resources/public/index.html。

最佳答案

问题出在函数 renderIndex() 中。使用正确的资源路径(即 /public/index.html)后,变量 url 不再为 null,但根据您在评论中所说的,它有些奇怪( jar:file:/home/gorrtack/workspace/Farot/target/Farot-1.0-SNA‌PSHOT-jar-with-depen‌ dencies.jar!/public/‌ index.html),一些与没有有效的路径

Paths.get() 尝试解析此路径时失败并抛出 NoSuchFileException(这是一个 IOException)。然后,您在 catch block 中捕获它,并返回 null。返回 null 是错误的,这就是您收到错误 404 的原因。

所以你需要:

  1. 更改项目结构,使 index.html 的路径正确。那么您将避免这种情况下的问题。
  2. 正确处理异常,意味着 - 不返回 null。决定在这些情况下要做什么,然后,如果需要,您仍然可以向客户端提供正常的错误消息和/或使用 request.status() API 或任何 any other response APIs自行设置响应状态。

关于Java、Spark、返回index.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44257072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com