【发布时间】:2018-03-15 23:04:30
【问题描述】:
那是我的班级休息控制器:
@RestController
@RequestMapping("/adiantamento-api/adiantamento")
@CrossOrigin(origins = "http://localhost:4200")
public class RelatorioController {
.....
}
这是我生成报告的方法,在 RelatorioController 里面
@RequestMapping(path="gerar-relatorio/", method = RequestMethod.GET)
public void gerarRelatorio(HttpServletResponse response) throws Exception {
try {
String nomeRelatorio = "RelAdvertenciaDB";//JsonUtils.getProperty(parametros, "nome_relatorio", "x", String.class);
Map<String, Object> reportParameters = new HashMap<>();
DatabaseContextHolder.set(DatabaseEnvironment.CICLOCAIRU);
reportParameters.put("CODIGO", 880);
InputStream reportStream = new ClassPathResource("relatorios/" + nomeRelatorio + ".jrxml").getInputStream();
JasperReport jasper = JasperCompileManager.compileReport(reportStream);
JRSaver.saveObject(jasper, "report.jasper");
JasperPrint jasperPrint = JasperFillManager.fillReport(jasper, reportParameters, jdbctemplate.getDataSource().getConnection());
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(
new SimpleOutputStreamExporterOutput("src\\main\\resources\\relatorios\\gerados\\"+nomeRelatorio+".pdf"));
SimplePdfReportConfiguration reportConfig
= new SimplePdfReportConfiguration();
reportConfig.setSizePageToContent(true);
reportConfig.setForceLineBreakPolicy(false);
SimplePdfExporterConfiguration exportConfig
= new SimplePdfExporterConfiguration();
exportConfig.setMetadataAuthor("JETERSON");
exporter.setConfiguration(reportConfig);
exporter.setConfiguration(exportConfig);
exporter.exportReport();
File file = new File("src\\main\\resources\\relatorios\\gerados\\"+nomeRelatorio+".pdf");
try(InputStream is = new FileInputStream(file);OutputStream out = response.getOutputStream()){
response.reset();
response.setContentType("application/pdf");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename="+nomeRelatorio+".pdf");
IOUtils.copy(is, out);
out.flush();
}
}catch (Exception e) {
throw new Exception(e);
}
}
我的 Cors 过滤器
@Configuration
@EnableWebMvc
public class WebConfigCors extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
我不知道这是否重要,但这是我的身份验证类别
public class TokenAuthenticationService {
// EXPIRATION_TIME = 10 dias
static final long EXPIRATION_TIME = 860_000_000;
static final String SECRET = "MySecret";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";
static void addAuthentication(HttpServletResponse response, String username) {
String JWT = Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
response.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Expose-Headers", HEADER_STRING);
}
static Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
// faz parse do token
String user = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody()
.getSubject();
if (user != null) {
return new UsernamePasswordAuthenticationToken(user, null, Collections.emptyList());
}
}
return null;
}
}
该项目有许多客户端 Angular 请求的控制器,但只有我的类 RelatorioController 抛出错误 cors,当生成 report Jasper 我在浏览器中收到错误 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
我怀疑这是因为jasper reposrts 它尽管毫无意义
如果我评论所有负责生成报告的行代码,则请求有效
编辑:这是我的角度调用
emitirAdvertencia(parametros: Object): any {
parametros['dbenv'] = ApplicationContext.getInstance().getDbenv();
parametros['usuario'] = ApplicationContext.getInstance().getUser().codigoUsuario;
parametros['nome_relatorio'] = 'RelAdvertenciaDB';
var httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/pdf',
'Authorization': this.localStorage.get('token'),
// all others methods not need this
'Access-Control-Allow-Origin': '*'
}),
responseType: 'blob' as 'blob',
};
return this.http.get(ApplicationContext.URL + '/adiantamento/gerar-relatorio/', httpOptions)
.map((res) => {
return new Blob([res], { type: 'application/pdf' });
});
}
【问题讨论】:
标签: angular spring-mvc spring-boot jasper-reports