如下示例演示如何使用Spring Web MVC框架生成JSON數據格式。首先使用Eclipse IDE,並按照如下步驟使用Spring Web Framework開發基於動態表單的Web應用程序:java
com.yiibai.springmvc
包下建立三個Java類:User
和 UserController
。CLASSPATH
中。完整的項目文件目錄結構以下所示 -web
User.java 的代碼以下所示 -spring
package com.yiibai.springmvc; public class User { private String name; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
UserController.java 的代碼以下所示 -spring-mvc
package com.yiibai.springmvc; 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(1100); return user; } }
GenerateJson-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.yiibai.springmvc" /> <mvc:annotation-driven /> </beans>
在上面的代碼中建立了一個簡單的POJO用戶,在UserController
中返回了User
對象。 Spring基於類路徑中的RequestMapping
和Jackson jar
自動處理JSON轉換。mvc
完成建立源和配置文件後,發佈應用程序到Tomcat服務器。app
如今啓動Tomcat服務器,當訪問URL => http://localhost:8080/GenerateJson/user/yiibai , 若是Spring Web應用程序沒有問題,應該看到如下結果:框架