【发布时间】:2016-08-26 00:18:50
【问题描述】:
我正在构建一个 RESTful API 并拥有一个 Spring REST 控制器 (@RestController) 和一个基于注释的配置。我想让我的项目的欢迎文件成为带有 API 文档的 .html 或 .jsp 文件。
在其他网络项目中,我会在 web.xml 中放置一个欢迎文件列表,但在这个特定项目中,我似乎无法让它工作(最好使用 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 控制器的一小部分
@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>和<welcome-file>的web.xml。 (没有运气) - 将 Controller 中的
@RequestMapping("/categories")从类级别移动到所有方法,并添加带有@RequestMapping("/")的新方法,该方法返回带有视图名称的String或ModelAndView。 (前者只是返回一个带有字符串的空白页,后者找不到映射) - 正如建议的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)
【问题讨论】:
-
对于索引控制器,不要使用
@RestController,而是使用@Controller。否则你会得到你描述的行为刚刚返回一个带有字符串的空白页...
标签: java spring annotations web.xml spring-restcontroller