אנטוטציה Spring RestController
אנטוטציה Spring RestController היא אנטוטציה נוחה שכותרת עצמה עם @Controller ו־@ResponseBody
. אנטוטציה זו מיושבת על ידי קלאס כדי לסמן אותו כקובץ טיפול בבקשות. אנטוטציה Spring RestController משמשת ליצירת שירותי רשת RESTful באמצעות Spring MVC. היא טופלת בהמרת נתוני הבקשה למתודת טיפול המוגדרת. לאחר שהתגובה נוצרה ממתודת הטיפול, היא ממירה אותה לתגובת JSON או XML.
דוגמה ל־Spring RestController
בואו נראה כיצד ניתן להשתמש ב־RestController ליצירת שירות רשת REST ב־Spring. נשתמש שוב במימוש של מאגר Spring וניצור שירות אינטרנט RESTful. ניצור אפליקציה ווב עצמאית ולא נשתמש ב־Spring Boot כאן. נחשף גם את ה־API שלנו כך שיתמוך בשני פורמטים, JSON ו־XML, בבקשה ובתגובה. בתמונה למטה מוצגת מבנה הפרויקט הסופי שלנו.
Spring RestController Maven Dependencies
בואו נבחן את התלויות הנדרשות כדי ליצור את פרויקט דוגמת ה־Spring RestController שלנו.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<!-- Jackson for REST JSON Support -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
<!-- JAXB for XML Response, needed to explicitly define from Java 9 onwards -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
<version>1.2.0</version>
</dependency>
אנו זקוקים לספריות Spring MVC, Jackson ו־JAXB כדי לתמוך בבקשות ותגובות XML ו־JSON משירות ה־REST שלנו. קובץ ה־web.xml שלנו משמש להגדרת DispatcherServlet של Spring MVC כפועל החזית. בואו נסתכל עכשיו על קובץ ה־Spring Context.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<context:component-scan
base-package="com.journaldev.spring" />
<beans:bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
<beans:bean id="xmlMessageConverter"
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter" />
<beans:ref bean="xmlMessageConverter" />
</beans:list>
</beans:property>
</beans:bean>
</beans:beans>
החלק החשוב ביותר הוא ה־beanים jsonMessageConverter
ו־xmlMessageConverter
המוגדרים ומוגדרים במאפיין messageConverters
של RequestMappingHandlerAdapter
. כל מה שנדרש הוא להגיד ל־Spring שאנו רוצים שיישום שלנו יתמוך בשני הפורמטים JSON ו־XML ואלה ה־beanים שיש להשתמש בהם להמרה.
Spring RestController Class
כאן תוכלו למצוא את מימוש מחלקת ה־Spring RestController שלנו.
package com.journaldev.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.journaldev.spring.model.Employee;
import com.journaldev.spring.repository.EmployeeRepository;
@RestController
public class EmployeeRestController {
@Autowired
private EmployeeRepository repository;
@GetMapping("/rest/employee/get/{id}")
public Employee getEmployeeByID(@PathVariable("id") int id) {
return repository.retrieve(id);
}
@GetMapping("/rest/employee/getAll")
//החזרת רשימה נתמכת רק עם תגובת JSON
//אם ברצונך XML, אז תוסיף מחלקת עטיפה כרכיב XML ראשי, לדוגמה EmployeeList
public List getAllEmployees() {
return repository.getAll();
}
@PostMapping("/rest/employee/create")
public Employee createEmployee(@RequestBody Employee emp) {
repository.store(emp);
return emp;
}
@GetMapping("/rest/employee/search/{name}")
public Employee getEmployeeByName(@PathVariable("name") String name) {
return repository.search(name);
}
@DeleteMapping("/rest/employee/delete/{id}")
public Employee deleteEmployeeByID(@PathVariable("id") int id) {
return repository.delete(id);
}
}
שים לב שהגדרנו רק את ה-REST APIs שלנו כאן, כל הלוגיקה העסקית היא חלק ממחלקת המאגר. אם השיטה שלנו מחזירה רשימה או מערך, אז Spring יתמוך רק בתגובת JSON מכיוון שאיבר השורש של XML לא יכול להיות אנונימי, אך JSON יכול. אם ברצונך לתמוך בהחזרת רשימה כ-XML, אז עליך ליצור מחלקת אריזה שתחזיק את הרשימה ותחזיר אותה. אנו מצפים לאובייקט Employee כבקשה בכמה מתוך השיטות, Spring יטפל בפריסת גוף הבקשה ובהמרתו לאובייקט Employee עבור שיטות אלו. באותה מידה, אנו מחזירים את אובייקט העובד כתגובה, שוב Spring יטפל בהמרתו לתגובה JSON/XML.
קבל וכותרת של בקשות הכוללות תכונות
הגדרנו את היישום שלנו של REST כך שיעבוד עם שני הפורמטים – XML ו-JSON. אז איך ידע שהבקשה היא XML או JSON? ואם התגובה צריכה להישלח בתצורה של JSON או XML? זהו המקום שבו משתמשים בכותרות בקשה של Accept
ו-Content-Type
. Content-Type: מגדיר את סוג התוכן בגוף הבקשה, אם הערך שלו הוא "application/xml" אז Spring יתייחס לגוף הבקשה כמסמך XML. אם הערך שלו הוא "application/json" אז גוף הבקשה יתייחס כ-JSON. Accept: מגדיר את סוג התוכן שהלקוח מצפה לו כתגובה. אם הערך שלו הוא "application/xml" אז יתבצע שליחת תגובה בתצורת XML. אם הערך שלו הוא "application/json" אז יתבצע שליחת תגובה בתצורת JSON.
בדיקת RestController של Spring
היישום שלנו מוכן לבדיקה, הפצתי אותו על Tomcat-9 ואני בודק בעזרת Postman. למטה מופיעים תוצאות הבדיקה עם ההסבר.
תגובת JSON מבדיקת Spring RestController GET
זו בקשת GET פשוטה, הנקודה החשובה לציין היא ערך ה- "Accept" בכותרת.
תגובת XML מבדיקת Spring RestController GET
כאשר שינינו את ערך ה- "Accept" לערך "application/xml", אנו מקבלים תגובת XML.
רשימת GET מבדיקת Spring RestController
נסה לקרוא ל- API כדי לקבל רשימת עובדים. אנו מקבלים רשימת אלמנטים ב- JSON עם אלמנט שורש אנונימי.
מאחר ו- XML אינו תומך באלמנט שורש אנונימי, אנו מקבלים הודעת חריגה.
Spring RestController POST
Spring RestController POST עם JSON בקשה ותגובה Spring RestController POST עם JSON גוף בקשה
Spring RestController POST עם JSON בקשה ותגובה ב- XML
Spring RestController DELETE
סיכום
ה-RestController של Spring מסייע לנו להתמקד בלוגיקה העסקית על ידי טיפול בכל המצרים הרגילים ליצירת API של שירותי REST.
ניתן להוריד את הפרויקט השלם ממערכת ה-GitHub שלנו.
Source:
https://www.digitalocean.com/community/tutorials/spring-restcontroller