📅  最后修改于: 2020-11-11 06:36:01             🧑  作者: Mango
以下示例显示了如何使用Spring Web MVC Framework生成JSON。首先,让我们拥有一个运行良好的Eclipse IDE,并考虑以下步骤以使用Spring Web Framework开发基于动态表单的Web应用程序-
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. |
2 | Create a Java classes User, UserController under the com.tutorialspoint package. |
3 | Download Jackson libraries Jackson Core, Jackson Databind and Jackson Annotations from maven repository page. Put them in your CLASSPATH. |
4 | The final step is to create the content of all the source and configuration files and export the application as explained below. |
package com.tutorialspoint;
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;
}
}
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;
}
}
在这里,我们创建了一个简单的POJO用户,并在UserController中返回了该User。 Spring根据类路径中存在的RequestMapping和Jackson罐自动处理JSON转换。
完成创建源文件和配置文件后,导出应用程序。右键单击您的应用程序,使用“导出”→“ WAR文件”选项,然后将您的TestWeb.war文件保存在Tomcat的webapps文件夹中。
现在,启动Tomcat服务器,并确保您能够使用标准浏览器从webapps文件夹访问其他网页。尝试使用URL – http:// localhost:8080 / TestWeb / mahesh ,我们将看到以下屏幕。