为了账号安全,请及时绑定邮箱和手机立即绑定

使用一个 RequestBody 在使用 java Spring 的 post 方法中区分 xml

使用一个 RequestBody 在使用 java Spring 的 post 方法中区分 xml

蝴蝶刀刀 2023-06-04 19:46:32
我正在使用 Java Spring 引导编写 restApplication。我应该在春天写帖子请求。其中接受数据是text/xml。但是,在 post 方法的参数中出现的 Dto 可以更改类的名称,例如一次它可能会出现在以下视图中   <Request1><Head><head>    <id/>    <name/>    <surname/></head></Head></Request1>在同一 url 地址的请求中,它可能会出现在其他视图中   <Other1><Head><head>   </fio></head></Head></Other1>我如何一次为多个通用 xml 编写一个 post 方法。这可能在 Java spring 中做到吗??。我在 pyton 中看到可以只写分配给变量一些 response.data 就是这样   @RequestMapping(name = "/a",method = RequestMethod.POST,produces = MediaType.ALL_VALUE)    private ResponseEntity<String> get(@RequestBody String data) throws ParserConfigurationException, IOException, SAXException {        String temp = "";        for(int i = 0 ; i < data.length() ;i ++){            if(Character.isAlphabetic(data.charAt(i))  || Character.isDigit(data.charAt(i)) || data.charAt(i) == '<' || data.charAt(i) == '>' || data.charAt(i) == '/' ){                    temp += data.charAt(i);            }        }        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();        InputSource src = new InputSource();        src.setCharacterStream(new StringReader(temp));        Document doc = builder.parse(src);        String temp23 = doc.getDocumentURI();        System.out.println(temp23);        String id = doc.getElementsByTagName("id").item(0).getTextContent();        String name = doc.getElementsByTagName("userName").item(0).getTextContent();        //String pink = doc.getElementsByTagName("request").item(0).getTextContent();        System.out.println(id+" "+name+" "+temp23);        return ResponseEntity.ok(data);    }现在我从字符串中得到
查看完整描述

2 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

经过 1 天的搜索,我发现 Response 应该以字符串形式返回,并且在 Document 类的帮助下,我们可以从字符串中解析新的 xml,然后我们可以做我们应该做的事情。Request1 是其他请求中的第一个 xml 数据,它来自 Other1 xml数据没关系。


 @RequestMapping(name = "/a",method = RequestMethod.POST,produces = MediaType.ALL_VALUE)

private ResponseEntity<String> getIt(@RequestBody String path) throws ParserConfigurationException, IOException, SAXException {

    Document doc = DocumentBuilderFactory.newInstance()

            .newDocumentBuilder()

            .parse(new InputSource(new StringReader(path)));

   if(path.contains("Request1")){

    NodeList tagName = doc.getElementsByTagName("id");

    if(tagName.getLength() > 0){

        System.out.println(tagName.item(0).getTextContent());

    }


   }

   if(path.contains("Other1")){

        NodeList tagName = doc.getElementsByTagName("fio");

        if(tagName.getLength() > 0){

            System.out.println(tagName.item(0).getTextContent());

        }

   }

    return ResponseEntity.ok("SAVED");


}


查看完整回答
反对 回复 2023-06-04
?
慕的地6264312

TA贡献1817条经验 获得超6个赞

好的,当你在响应中有不同的数据时,你想得到不同的结果吗?如果是,那么请处理控制器内的视图,您想为该响应显示哪个视图。

我希望这会帮助你理解。


查看完整回答
反对 回复 2023-06-04
  • 2 回答
  • 0 关注
  • 117 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信