带有文件扩展名的Java Spring结束URL

时间:2018-11-13 07:15:57

标签: java spring

我有一个返回字符串的服务。字符串采用XML形式。 URL是/ monitoring。但是客户端现在希望URL以/status.xml结尾。我怎么做?我试图更改GetMapping中的值,但随后它停止工作。以status.xml结尾的URL有什么特别的,我该如何实现?

@GetMapping(value = "/monitoring")
public ResponseEntity getStatuses() throws TransformerException, UnsupportedEncodingException, JAXBException {
    return indexService.getStatusEntity();
}

public ResponseEntity getStatusEntity() throws JAXBException, UnsupportedEncodingException, TransformerException {
        byte[] xml = getStatus();
        String xmlStr = new String(xml, "UTF-8");
        xmlStr = xmlStr.replaceAll("<", "<");
        xmlStr = xmlStr.replaceAll(">", ">");
        Source src = new StreamSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        StreamResult result = new StreamResult(bos);
        transformer.transform(src, result);

        return setDocumentHeaderAndReturnOK(bos.toByteArray());
    }

private byte[] getStatus() throws JAXBException {
    String tomcat = ServerInfo.getServerInfo();
    String[] pieces = tomcat.split("/");
    App status = new App(applicationInfoService.getVersion().getBody(), "name", "OK", "",
        new ServerPlatform(pieces[1], pieces[0]), new RunTimeEnvironment(System.getProperty("java.version"), "JAVA"),
        checkExternalDependencies());

    QName main = new QName("app");
    JAXBElement<App> root = new JAXBElement<>(main, App.class, status);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    JAXBContext jaxbContext = JAXBContext.newInstance(App.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(root, out);
    jaxbMarshaller.marshal(root, System.out);

    return out.toByteArray();
}

    @Transactional
public ResponseEntity setDocumentHeaderAndReturnOK(byte[] contents) {

    HttpHeaders headers = new HttpHeaders();

    String fileType = "xml";

    String filename = "status.xml";
    headers.setContentType(MediaType.parseMediaType("application/" + fileType));

    headers.add("Content-Disposition", "inline; filename=" + filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

    return new ResponseEntity(contents, headers, HttpStatus.OK);

编辑:

我尝试用jaxb生成类,并使用它们来生成XML。但这不会更改网址。我已经正确生成了XML内容,我只需要一种将GetMapping从/ monitoring到/status.xml的方法。拥有status.xml形式的url甚至意味着什么?

0 个答案:

没有答案