以下示例演示如何使用spring web mvc框架生成json数据格式。首先使用eclipse ide,并按照以下步骤使用spring web framework开发基于动态表单的web应用程序:
com.h3.springmvc
包下创建三个java类:user
和 usercontroller
。classpath
中。完整的项目文件目录结构如下所示 -
user.java 的代码如下所示 -
package com.h3.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 的代码如下所示 -
package com.h3.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.h3.springmvc" />
<mvc:annotation-driven />
</beans>
在上面的代码中创建了一个简单的pojo用户,在usercontroller
中返回了user
对象。 spring基于类路径中的requestmapping
和jackson jar
自动处理json转换。
完成创建源和配置文件后,发布应用程序到tomcat服务器。
现在启动tomcat服务器,当访问url => http://localhost:8080/generatejson/user/h3 , 如果spring web应用程序没有问题,应该看到以下结果: