javascript
Spring MVC –使用@ResponseBody轻松实现基于REST的JSON服务
Spring 3使JSON REST服務非常容易。 本教程將通過幾個步驟向您展示如何進行。 您可以在GitHub上獲取代碼。
先決條件
您應該有一個運行中的Spring MVC應用程序。 如果尚未設置正常的Spring MVC應用程序,請按照本教程進行操作 。 我們將定義三個REST服務:1)檢索隨機的Person,2)按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(value="person", params="id")@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(value="person", method=RequestMethod.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:
<dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.12</version> </dependency>或者,如果您希望服務返回XML,則包括您喜歡的Jaxb實現。 com.sun.xml.bind:jaxb:2.1.9 。
稍后,我們將構建一個前端,以使用AJAX調用這些服務,但是如果您現在部署應用程序,則可以使用REST客戶端(或僅在瀏覽器中鍵入URL)試用您的服務。 例如:
如果您對此感到滿意,可以停止關注。 現在,我將通過編碼客戶端jQuery來連接所有組件:
home.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><!DOCTYPE HTML> <html><head><title>Spring MVC - Ajax</title><script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><style>body { 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></head><body><div id="container"><h1>Person Page</h1><p>This page demonstrates Spring MVC's powerful Ajax functionality. Retrieve arandom person, retrieve a person by ID, or save a new person, all without page reload.</p><h2>Random Person Generator</h2><input type="submit" id="randomPerson" value="Get Random Person" /><br/><br/><div id="personResponse"> </div><hr/><h2>Get By ID</h2><form id="idForm"><div class="error hide" id="idError">Please enter a valid ID in range 0-3</div><label for="personId">ID (0-3): </label><input name="id" id="personId" value="0" type="number" /><input type="submit" value="Get Person By ID" /> <br /><br/><div id="personIdResponse"> </div></form><hr/><h2>Submit new Person</h2><form id="newPersonForm"><label for="nameInput">Name: </label><input type="text" name="name" id="nameInput" /><br/><label for="ageInput">Age: </label><input type="text" name="age" id="ageInput" /><br/><input type="submit" value="Save Person" /><br/><br/><div id="personFormResponse" class="green"> </div></form></div><script type="text/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:// localhost:8080。
參考文獻
- SpringSource博客– Spring MVC Ajax的簡化
- SpringSource博客– Spring MVC增強功能
翻譯自: https://www.javacodegeeks.com/2013/04/spring-mvc-easy-rest-based-json-services-with-responsebody.html
總結
以上是生活随笔為你收集整理的Spring MVC –使用@ResponseBody轻松实现基于REST的JSON服务的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 剧情安卓游戏推荐(剧情安卓游戏)
- 下一篇: 深圳对外贸易经营者备案登记流程(深圳对外