我正在尝试使用spring boot返回一个静态html(index.html
)页面,但是当我尝试(http://localhost:8080/)时,我总是得到405错误。奇怪的事实是调试器输入index()
方法。
HomeController:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "index.html";
}
}
我试图返回"index.html"
和" index"字符串。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext applicationContext
= SpringApplication.run(Application.class, args);
}
}
html文件的位置是:
src\main\resources\public\index.html
这里是启动记录器输出的一部分:
INFO 8284 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/],methods=[GET]}" onto public java.lang.String com.acs.map.controller.HomeController.index()
我正在使用gradle运行项目:gradle bootRun
请求后的记录消息:
WARN 3988 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound : Request method 'GET' not supported
此外,我尝试过使用和不使用此配置:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/public/**").addResourceLocations("classpath:/public/");
registry.addResourceHandler("/resources/public/**").addResourceLocations("classpath:/resources/public/");
super.addResourceHandlers(registry);
}
@Bean
public ViewResolver viewResolver() {
UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
viewResolver.setViewClass(InternalResourceView.class);
return viewResolver;
}
}
答案 0 :(得分:2)
默认情况下,Spring Boot将从名为/ static(或/ public或/ resources或/ META-INF / resources)的目录中提供静态内容。我按照以下结构快速检查并取得了成功。
所以我相信通过扩展WebMvcConfigurerAdapter类,如下所示,它应该使用您当前的控制器代码返回静态内容(没有WebConfig类)。您也可以使用viewResolver在视图名称和实际视图之间进行映射,同时进一步修改您的码。
@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}