在Spring Boot 1.3.0应用程序中,我试图使用单一控制器方法仅根据路径生成HTML和CSV格式的响应(无内容协商):
@Controller
@RequestMapping("/report")
public class ReportController {
@RequestMapping(value = "report.{fileExt}", method = RequestMethod.GET)
public String report(@PathVariable String fileExt, Model model) {
// add stuff to the Model instance
return fileExt + "Report";
}
}
为了处理HTML格式,我有一个src\resources\templates\htmlReport.tpl
Groovy模板。当我访问/app/report.html时,Spring Boot能够很好地定位和调用模板。
要处理CSV格式,我有一个自定义视图:
@Component
public class ReportCsvView extends AbstractView {
@Override
public String getContentType() {
return "text/csv";
}
@Override
protected void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
PrintWriter writer = response.getWriter();
// write CSV to writer
}
}
自定义ViewResolver以注册我的自定义视图
@Configuration
public class ReportCsvViewConfigurer extends WebMvcConfigurerAdapter {
@Autowired
private ReportCsvView reportCsvView;
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(new ViewResolver() {
@Override
public View resolveViewName(String name, Locale locale) throws Exception {
return "csvReport".equals(name) ? reportCsvView : null;
}
});
super.configureViewResolvers(registry);
}
}
问题在于,当我点击/app/report.csv时,会调用匿名ViewResolver的resolveViewName
方法,并返回返回ReportCsvView
实例的分支。到现在为止还挺好。但是,renderMergedOutputModel
未被调用(尽管getContentType
方法被调用两次),导致HTTP 404响应。
如何让我的视图实际渲染?
更新我删除了getContentType
方法的覆盖;结果,renderMergeOutputModel
现在被调用。