perwendel / spark

A simple expressive web framework for java. Spark has a kotlin DSL https://github.com/perwendel/spark-kotlin
Apache License 2.0
9.63k stars 1.56k forks source link

Unable to serve static file using Spark Java #1281

Closed rollno748 closed 10 months ago

rollno748 commented 10 months ago

Hi,

My project structure looks like the below:

image

And I have the below code - which is configured to serve static web page within the package (src/main/resources/public)

Which is not working and i don't see any exception in the logs as well

 public void startRestServer() {
        try {
            port(serverPort);
//            staticFiles.location(System.getProperty("user.dir") + "/src/main/resources/public/");
            staticFiles.location("/public");
            connectionPool = SQLiteConnectionPool.getInstance(fileServerLocation, MIN_THREADS, MAX_THREADS, TIMEOUT);
            staticFiles.externalLocation(this.fileServerLocation);
            init();
            awaitInitialization();
            loadRestApiServices();
            LOGGER.debug(String.format("REST services started :: http://%s:%s%s/",
                    InetAddress.getLocalHost().getHostAddress(), serverPort, uriPath));
        } catch (Exception e) {
            LOGGER.error("REST services failed to start", e);
        }
    }

I have API path configured below

public void loadRestApiServices() {
        UploadService uploadService = new UploadServiceImpl();
        path(RestController.uriPath, () -> {
            before("/*", (req, res) -> LOGGER.info("Received api call"));

            get("/greet", (req, res) -> {
                return "Hello Work !";
            });

            post("/upload", (req, res) -> {
                JSONObject jsonObject = new JSONObject(req.body());
                uploadService.uploadCustomPlugin(jsonObject);
                return null;
            });

            after((req, res) -> res.header("Content-Encoding", "gzip"));

        });

I am stuck with this - could someone help me to proceed further ? I have posted the query in stackoverflow as well, didn't get any response

kamenitxan commented 10 months ago

Hi, on which url are you trying to access static files?

With this staticFiles.location("/public");

I think it should be "http://localhost:4567/script.js". I´m using static files in my project, maybe it will help you https://github.com/kamenitxan/Jakon/blob/master/modules/backend/src/main/scala/cz/kamenitxan/jakon/JakonInit.scala

rollno748 commented 10 months ago

Hi,

I am able to access it using root path (http://localhost:2222/index.html or http://localhost:2222/)

The issue was due to an groovy dependency library which was added by mistake.

I apologise, i failed to update it here