首页 > 解决方案 > 带有文件扩展名的 Java Spring 结束 URL

问题描述

我有一个返回字符串的服务。字符串是 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 甚至意味着什么?

标签: javaspring

解决方案


推荐阅读