Spring MVC - 生成 XML 示例



以下示例演示瞭如何使用 Spring Web MVC 框架生成 XML。首先,讓我們準備好一個可用的 Eclipse IDE,並按照以下步驟使用 Spring Web 框架開發基於動態表單的 Web 應用程式。

步驟 描述
1 在 Spring MVC - Hello World 章節中說明的包 com.tutorialspoint 下建立一個名為 TestWeb 的專案。
2 在 com.tutorialspoint 包下建立 Java 類 User 和 UserController。
3 最後一步是建立原始檔和配置檔案的內容,並按如下所述匯出應用程式。

User.java

package com.tutorialspoint;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User {
   private String name;
   private int id;
   public String getName() {
      return name;
   }
   @XmlElement
   public void setName(String name) {
      this.name = name;
   }
   public int getId() {
      return id;
   }
   @XmlElement
   public void setId(int id) {
      this.id = id;
   }	
}

UserController.java

package com.tutorialspoint;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {
	
   @RequestMapping(value="{name}", method = RequestMethod.GET)
   public @ResponseBody User getUser(@PathVariable String name) {

      User user = new User();

      user.setName(name);
      user.setId(1);
      return user;
   }
}

TestWeb-servlet.xml

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"   
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:mvc = "http://www.springframework.org/schema/mvc"
   xsi:schemaLocation = "
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
   <context:component-scan base-package = "com.tutorialspoint" />
   <mvc:annotation-driven />
</beans>

在這裡,我們建立了一個 XML 對映 POJO User,在 UserController 中,我們返回了 User。Spring 根據 **RequestMapping** 自動處理 XML 轉換。

建立完原始檔和配置檔案後,匯出您的應用程式。右鍵單擊您的應用程式,使用 **匯出 → WAR 檔案** 選項並將您的 **TestWeb.war** 檔案儲存在 Tomcat 的 webapps 資料夾中。

現在,啟動 Tomcat 伺服器,並確保您可以使用標準瀏覽器從 webapps 資料夾訪問其他網頁。嘗試 URL – **https://:8080/TestWeb/mahesh**,我們將看到以下螢幕。

Spring XML Generation
廣告

© . All rights reserved.