-->

Sparkjava redirect while keeping the browser URL

2019-07-23 20:53发布

问题:

I have a sparkjava server app running, it serves a static HTML page using this line:

staticFiles.location("/public");

If you go to http://example.com, you will see the HTML page. Now, I want to redirect users from other paths to my homepage, while keeping the browser URL. For example, if you visit http://example.com/message/123, you will still see the HTML page, while the browser URL stays http://example.com/message/123. So redirect.get() won't work here.

回答1:

In order to serve the same file from different paths, you can do as follows (it looks long but it's pretty simple):

Assuming your project's structure is:

src
  java
    main
      resources
        public
        templates   (optional folder)

On GET request to your homepage a static HTML file that resides in /public is served. Let's call this file index.html.

Now you want to register additional path(s) to serve this file. If you use TemplateEngine you can do it easily. Actually, you'll refer to index.html both as a static file and as a template (with no parameters).

Template engine lets you create the served HTML page dynamically by passing it a map of key-value pairs that you can reference in the template on runtime. But in your case, it will be much simpler because you want to serve a page as-is, statically. Therefore you'll pass an empty map:

Spark.get("/message/123", (req, res) ->
    new ModelAndView(new HashMap(),
                     "../public/index"),
                     new ThymeleafTemplateEngine()
);
  • Thymeleaf is just an example here, Spark supports few template engines. For each one of them, you can find in the documentation a simple github example of how to use it. For example, This is the Thymeleaf one.
  • The path ../public/index is because Spark is looking for templates in the templates folder, and you want to target public/index.html as the template.
  • You'll find the class ThymeleafTemplateEngine in the github link.
  • Of course you'll have to add the chosen template engine dependency to the project's pom.xml file.

As a result, GET requests to both http://example.com and http://example.com/message/123 will serve index.html while keeping the requested URL.



标签: spark-java