JAXB-Marshaller写入系统输出但不写入XML文件

问题描述 投票:0回答:1

我目前正在开发旅行服务,我们必须使用JAXB编组将用户信息写入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个回答
0
投票

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

您需要使用File文件中的File对象= new File(“ / tmp / accounts.xml”)

© www.soinside.com 2019 - 2024. All rights reserved.