有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring引导映射静态html

我想创建SpringBootWeb应用程序

我有两个静态html文件:一个。html,两个。html

我想把它们映射如下

localhost:8080/one
localhost:8080/two

不使用模板引擎(Thymeleaf)

怎么做?我已经尝试了很多方法,但是我有404错误或500错误(循环视图路径[one.html]:将发送回当前处理程序URL)

一个控制器。java是:

@Controller
public class OneController {
    @RequestMapping("/one")
    public String one() {
        return "static/one.html";
    }
}

项目结构为

enter image description here


共 (4) 个答案

  1. # 1 楼答案

    请更新您的WebMvcConfig并包括UrlBasedViewResolver和/或静态资源处理程序。Mine WebConfig类如下所示:

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
            super.addResourceHandlers(registry);
        }
    
        @Bean
        public ViewResolver viewResolver() {
            UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
            viewResolver.setViewClass(InternalResourceView.class);
            return viewResolver;
        }
    
    }
    

    我已经检查过了,看起来很有效

    Maciej的答案基于浏览器的重定向。我的解决方案返回静态,没有浏览器交互

  2. # 2 楼答案

    我是第一次和百里哀拉夫在一起,花了一个小时试图弄明白这一点

    在“application.properties”中添加

    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.suffix=.html
    
    
  3. # 3 楼答案

    在我的例子中,我希望将所有子路径映射到同一个文件,但保持浏览器路径为原始请求的路径,同时使用thymeleaf,那么我不想覆盖它的解析器

    @Controller
    public class Controller {
    
        @Value("${:classpath:/hawtio-static/index.html}")
        private Resource index;
    
        @GetMapping(value = {"/jmx/*", "/jvm/*"}, produces = MediaType.TEXT_HTML_VALUE)
        @ResponseBody
        public ResponseEntity actions() throws IOException {
            return ResponseEntity.ok(new InputStreamResource(index.getInputStream()));
        }
    }
    

    Obs。每次点击都会从索引中读取数据。html文件,它将不会被缓存

  4. # 4 楼答案

    如果您不关心其他浏览器重定向,可以使用以下方法:

    @Controller
    public class OneController {
        @RequestMapping("/one")
        public String one() {
            return "redirect:/static/one.html";
        }
    }