gpt4 book ai didi

java - 设置 Spring REST Controller 欢迎文件

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

我正在构建一个 RESTful API,并拥有一个 Spring REST Controller (@RestController) 和一个基于注释的配置。我希望我的项目的欢迎文件是带有 API 文档的 .html 或 .jsp 文件。

在其他 Web 项目中,我会在 web.xml 中放置一个welcome-file-list,但在这个特定项目中,我似乎无法让它工作(最好使用 Java 和注释)。

这是我的 WebApplicationInitializer

public class WebAppInitializer implements WebApplicationInitializer {

public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ApplicationConfig.class);
context.setServletContext(servletContext);

ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcher",
new DispatcherServlet(context));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}

这是我的 WebMvcConfigurerAdapter

@Configuration
@ComponentScan("controller")
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {

@Bean
public Application application() {
return new Application("Memory");
}

}

这是我的 REST Controller 的一小部分

@RestController
@RequestMapping("/categories")
public class CategoryRestController {

@Autowired
Application application;

@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<Integer, Category>> getCategories(){
if(application.getCategories().isEmpty()) {
return new ResponseEntity<Map<Integer, Category>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<Map<Integer, Category>>(application.getCategories(), HttpStatus.OK);
}

}

到目前为止我已经尝试过:

  • 仅添加带有 <welcome-file-list> 的 web.xml与 <welcome-file> 。 (没有运气)
  • 移动@RequestMapping("/categories")在 Controller 中从类级别到所有方法,并使用 @RequestMapping("/") 添加新方法,它返回 StringModelAndView与 View 名称。 (前者只是返回一个带有字符串的空白页,后者找不到映射)
  • 按照建议 here :两者的组合,其中我的 web.xml <welcome-file>是“/index”,与 @RequestMapping(value="/index") 组合返回 new ModelAndView("index") ,以及 ViewResolver在我的配置类中。 (返回 Warning: No mapping found in DispatcherServlet with name 'dispatcher' ,即使“/index”已成功映射。手动将“/index”添加到 URL 会成功将其解析为 index.jsp)

最佳答案

当指定 Controller 来处理索引页时,您应该使用@Controller而不是@RestController。尽管@RestController是一个@Controller,但它不会解析为 View ,而是将结果按原样返回给客户端。当使用@Controller返回String时,它将解析为 View 的名称。

@Controller
public class IndexController {

@RequestMapping("/")
public String index() {
return "index";
}
}

但是,有一种更简单的方法来配置它,并且您不需要 Controller 。配置 View Controller 。在您的配置类中,只需覆盖/实现 addViewControllers 方法即可。

public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}

这样你甚至不需要为它创建一个类。

关于java - 设置 Spring REST Controller 欢迎文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36962024/

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