【问题标题】:How to persist/save Objects in XML Spring MVC如何在 XML Spring MVC 中持久化/保存对象
【发布时间】:2014-07-08 12:45:16
【问题描述】:

我想将对象值保存在我的 Spring MVC 项目的 SRC 文件夹中的 xml 文件中。

我对 JAX-B 用于将对象保存到 xml 文件的编组和取消编组概念了解一些。

example ,
    Employee emp1=new Employee(1,"Robin",50000);  
    File file =new File("c://myfiles//employee.xml"))  
    marshallerObj.marshal(emp1, new FileOutputStream(file); 

上面的代码将 my emplyee 对象保存到位于 C/myfiles 文件夹中的 employee.xml 文件中。

那么我如何在 spring 控制器中使用相同的代码 如下图,

@RequestMapping(value="/saveNotice",method=RequestMethod.POST)
public void saveNotice(Notice notice){

    Employee emp1=new Employee(1,"Robin",50000);  
    File file =new File("src/employee.xml"))  
    marshallerObj.marshal(emp1, new FileOutputStream(file); 
}

在这里需要帮助............

谢谢。

【问题讨论】:

    标签: java xml spring spring-mvc jaxb


    【解决方案1】:

    朋友。

    1 假设 您的 src 文件夹是 c://workspace//myproject//src// 你的类输出文件夹是 c://workspace//myproject//WEB-ROOT//

    2 当你的类被tomcat调用时,tomcat会将“src/emplyee.xml”作为相对路径,并翻译成“c://workspace//myproject//WEB-ROOT//src//emplyee.xml” “ 最后 。 所以,filenotfoundexception 将被抛出。

    3 如果你真的想阅读 c://workspace//myproject//src// 中的 emplyee.xml 你可以使用绝对路径:

    文件file =new File("c://workspace//myproject//src//employee.xml"))

    或者您可以将您的employee.xml 移动到“c://workspace//myproject//WEB-ROOT//src//emplyee.xml”

    【讨论】:

    • ,我无法将完整路径直接传递给本地主机上的文件构造函数,因为我在 Windows 操作系统中工作,而我的实时服务器在 Linux 操作系统上。所以在这种情况下,employee.xml 文件路径会更改。我想要相对路径。
    • 试一试:File file =new File(this.getClass().getClassLoader().getResource("/").getPath()+"employee.xml")
    【解决方案2】:

    要编组一个对象,然后将其状态保存在位于类路径内的文件中,您必须执行以下步骤:

    1. 注释模型的对象

      @XmlRootElement
      @XmlAccessorType(XmlAccessType.FIELD)
      public class Employee {
      
      @XmlAttribute (required = true)
      private String id;
      @XmlAttribute (required = true)
      private String name;
      @XmlAttribute (required = true)
      private String salary;
      
      //Getter and setter method
      
      }
      
    2. 整理你的对象

      JAXBContext context = JAXBContext.newInstance(Employee.class);
      Marshaller m = context.createMarshaller();
      m.marshal(creditCard, new File("/employee.xml"));
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-28
      • 2016-11-14
      • 2018-05-01
      • 1970-01-01
      • 2011-04-09
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多