滨州正规网站建设公司,建个网站花钱做百度推广,外贸营销员,wordpress ico不显示Spring 3使JSON REST服务非常容易。 本教程将通过几个步骤向您展示如何进行。 您可以在GitHub上获取代码。 先决条件 您应该有一个运行中的Spring MVC应用程序。 如果尚未设置正常的Spring MVC应用程序#xff0c;请按照本教程进行操作 。 我们将定义三个REST服务#xff1a… Spring 3使JSON REST服务非常容易。 本教程将通过几个步骤向您展示如何进行。 您可以在GitHub上获取代码。 先决条件 您应该有一个运行中的Spring MVC应用程序。 如果尚未设置正常的Spring MVC应用程序请按照本教程进行操作 。 我们将定义三个REST服务1检索随机的Person2按ID检索Person以及3保存新的Person。 我们将在示例页面上使用jQuery使用这些服务。 首先我将展示用于REST服务的Spring Controller然后逐步介绍它们的工作方式 PersonController.java package com.codetutr.controller;import org.springframework.beans.factory.annotation.Autowired;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;import com.codetutr.domain.Person;
import com.codetutr.service.PersonService;Controller
RequestMapping(api)
public class PersonController {PersonService personService;Autowiredpublic PersonController(PersonService personService) {this.personService personService;}RequestMapping(person/random)ResponseBodypublic Person randomPerson() {return personService.getRandom();}RequestMapping(person/{id})ResponseBodypublic Person getById(PathVariable Long id) {return personService.getById(id);}/* same as above method, but is mapped to* /api/person?id rather than /api/person/{id}*/RequestMapping(valueperson, paramsid)ResponseBodypublic Person getByIdFromParam(RequestParam Long id) {return personService.getById(id);}/*** Saves new person. Spring automatically binds the name* and age parameters in the request to the person argument* param person* return String indicating success or failure of save*/RequestMapping(valueperson, methodRequestMethod.POST)ResponseBodypublic String savePerson(Person person) {personService.save(person);return Saved person: person.toString();}
} 好的因此如您所见该控制器中有4个请求处理程序。 第一种方法返回一个随机的人。 接下来的两个ID检索一个人–只是两种不同的URL映射方法。 最后一种方法可以保存一个人。 记住Spring控制器通常如何返回String类型以指示结果视图名称。 相反这里我们使用Spring的ResponseBody批注并返回要发送给客户端的对象。 ResponseBody注释告诉Spring我们将在响应主体中返回数据而不是呈现JSP。 当使用ResponseBody批注时Spring将以客户端可接受的格式返回数据。 也就是说如果客户端请求具有用于接受json的标头并且类路径中存在Jackson-Mapper则Spring将尝试将返回值序列化为JSON。 如果请求标头指示XML是可接受的accept application / xml并且Jaxb在类路径中并且返回类型使用Jaxb注释进行注释则Spring将尝试将返回值编组为XML。 如前所述如果您希望服务返回JSON则必须在类路径中包含Jackson。 这是您需要添加到项目中的唯一依赖项 Gradle compile org.codehaus.jackson:jackson-mapper-asl:1.9.12 或者如果您使用的是Maven dependencygroupIdorg.codehaus.jackson/groupIdartifactIdjackson-mapper-asl/artifactIdversion1.9.12/version
/dependency 或者如果您希望服务返回XML则包括您喜欢的Jaxb实现。 com.sun.xml.bind:jaxb:2.1.9 。 稍后我们将构建一个前端以使用AJAX调用这些服务但是如果您现在部署应用程序则可以使用REST客户端或仅在浏览器中键入URL试用您的服务。 例如 如果您对此感到满意可以停止关注。 现在我将通过编码客户端jQuery来连接所有组件 home.jsp % taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
% taglib prefixform urihttp://www.springframework.org/tags/form %!DOCTYPE HTML
htmlheadtitleSpring MVC - Ajax/titlescript src//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js/scriptstylebody { background-color: #eee; font: helvetica; }#container { width: 500px; background-color: #fff; margin: 30px auto; padding: 30px; border-radius: 5px; box-shadow: 5px; }.green { font-weight: bold; color: green; }.message { margin-bottom: 10px; }label { width:70px; display:inline-block;}.hide { display: none; }.error { color: red; font-size: 0.8em; }/style/headbodydiv idcontainerh1Person Page/h1pThis page demonstrates Spring MVCs powerful Ajax functionality. Retrieve arandom person, retrieve a person by ID, or save a new person, all without page reload./ph2Random Person Generator/h2input typesubmit idrandomPerson valueGet Random Person /br/br/div idpersonResponse /divhr/h2Get By ID/h2form ididFormdiv classerror hide ididErrorPlease enter a valid ID in range 0-3/divlabel forpersonIdID (0-3): /labelinput nameid idpersonId value0 typenumber /input typesubmit valueGet Person By ID / br /br/div idpersonIdResponse /div/formhr/h2Submit new Person/h2form idnewPersonFormlabel fornameInputName: /labelinput typetext namename idnameInput /br/label forageInputAge: /labelinput typetext nameage idageInput /br/input typesubmit valueSave Person /br/br/div idpersonFormResponse classgreen /div/form/divscript typetext/javascript$(document).ready(function() {// Random Person AJAX Request$(#randomPerson).click(function() {$.getJSON(${pageContext.request.contextPath}/api/person/random, function(person) {$(#personResponse).text(person.name , age person.age);});});// Request Person by ID AJAX$(#idForm).submit(function(e) {var personId $(#personId).val();if(!validatePersonId(personId)) return false;$.get(${pageContext.request.contextPath}/api/person/ personId, function(person) {$(#personIdResponse).text(person.name , age person.age);});e.preventDefault(); // prevent actual form submit});// Save Person AJAX Form Submit$(#randomPerson).click(function() {$.getJSON(${pageContext.request.contextPath}/api/person/random, function(person) {$(#personResponse).text(person.name , age person.age);});});$(#newPersonForm).submit(function(e) {// will pass the form date using the jQuery serialize function$.post(${pageContext.request.contextPath}/api/person, $(this).serialize(), function(response) {$(#personFormResponse).text(response);});e.preventDefault(); // prevent actual form submit and page reload});});function validatePersonId(personId) {console.log(personId);if(personId undefined || personId 0 || personId 3) {$(#idError).show();return false;}else {$(#idError).hide();return true;}}/script/body
/html 一切就绪后您应该拥有一个如下所示的页面 完整资料 ZIP GitHub上 要运行本教程中的代码必须已安装Gradle 。 下载ZIP。 提取。 打开命令提示符以提取位置。 运行gradle jettyRunWar。 在浏览器中导航到http// localhost8080。 参考文献 SpringSource博客– Spring MVC Ajax的简化 SpringSource博客– Spring MVC增强功能 参考 Spring MVC –来自JCG合作伙伴 Steve Hanson的ResponseBody 提供的基于REST的基于REST的轻松JSON服务位于CodeTutr博客上。 翻译自: https://www.javacodegeeks.com/2013/04/spring-mvc-easy-rest-based-json-services-with-responsebody.html