【问题标题】:JAXB - Marshaller Writing to System Output But Not to XML FileJAXB - Marshaller 写入系统输出但不写入 XML 文件
【发布时间】:2020-02-26 20:40:19
【问题描述】:

我目前正在开发旅行服务,我们必须使用 JAXB Marshalling 将用户信息写入 XML 文件。在 Tomcat 服务器上运行应用程序时,我在文本框中输入信息并单击“注册”,XML 格式是在控制台中写入的,但实际上并没有写入 XML 文件。截至目前,我在“src/main/resources”目录中有我的“accounts.xml”。到目前为止,这是我的控制器信息。我不确定为什么它不会写入 XML 文件:

@Controller
public class AccountController {
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String registerPage(Locale locale, Model model) {
        return "register";
    }

    @RequestMapping(value = "/home", method = RequestMethod.POST)
    public String register(@RequestParam("name") String name, @Validated User user, Model model) throws JAXBException, IOException{

        Account account = new Account();
        account.setName(name);
        account.setEmail("email");
        account.setPassword("password");

        try {


            File file = ResourceUtils.getFile("classpath:accounts.xml");


            JAXBContext jaxbContext = JAXBContext.newInstance(Account.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            jaxbMarshaller.marshal(account, file);
            jaxbMarshaller.marshal(account, System.out);


              } catch (JAXBException e) {
                  e.printStackTrace();
              }


        model.addAttribute("name", user.getName());
        return "user";
    }


}

当我提交信息时,我的控制台输出如下所示:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<account>
    <email>email</email>
    <name>testName</name>
    <password>password</password>
</account>

任何帮助将不胜感激!

【问题讨论】:

  • 您好,如果任何答案解决了您的问题,请考虑通过单击复选标记接受它。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。

标签: java xml spring-mvc jaxb marshalling


【解决方案1】:

文件文件 = ResourceUtils.getFile("classpath:accounts.xml");是一个“java.io.File”对象,它引用类路径的文件accounts.xml 部分。这是部署在您的 tomcat 中的 war 文件的一部分。

您需要使用 File 对象,如 File file = new File("/tmp/accounts.xml")

【讨论】:

    【解决方案2】:

    如果你真的想这样做,你应该确保你的 WAR 部署是爆炸式的,并查看 accounts.xml 是否可写。看看这个:How can I save a file to the class path

    此外,我看到您在每个请求中都创建了一个 JAXBContext。 JAXB 规范说:

    为了避免创建 JAXBContext 实例所涉及的开销,一个 鼓励 JAXB 应用程序重用 JAXBContext 实例。一个 抽象类 JAXBContext 的实现必须是 线程安全,因此,应用程序中的多个线程可以共享 相同的 JAXBContext 实例。

    您应该将 JAXBContext 移动到静态字段,因为只需要一个实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多