المفسر في الإقلاع او التمهيد الربيع Spring Boot Interceptor#

المفسر في الإقلاع او التمهيد الربيع

 Spring Boot Interceptor#

المفسر في الإقلاع او التمهيد الربيع Spring Boot Interceptor#
يمكنك استخدام Interceptor في Spring Boot لإجراء عمليات في المواقف التالية -

 قبل إرسال الطلب إلى وحدة تحكم

 قبل إرسال الرد على العميل

 على سبيل المثال ، يمكنك استخدام أداة اعتراض او التفسير لإضافة تعليمة الطلب قبل إرسال الطلب إلى وحدة التحكم وإضافة تعليمة الاستجابة قبل إرسال الاستجابة إلى العميل.

 للعمل مع المعترض ، تحتاج إلى إنشاء فئةComponent تدعمها ويجب أن تقوم بتطبيق واجهة HandlerInterceptor.

 فيما يلي الطرق الثلاث التي يجب أن تعرفها أثناء العمل على أجهزة التفسير -

طريقة preHandle () - يستخدم هذا لتنفيذ العمليات قبل إرسال الطلب إلى وحدة التحكم.  يجب أن ترجع هذه الطريقة true لإرجاع الاستجابة إلى العميل.

 طريقة postHandle () - يتم استخدام هذا لتنفيذ العمليات قبل إرسال الاستجابة إلى العميل.

 afterCompletion () طريقة - يستخدم هذا لتنفيذ العمليات بعد إكمال الطلب والاستجابة.

 لاحظ الكود التالي لفهم أفضل -


@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
   @Override
   public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      
      return true;
   }
   @Override
   public void postHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler, 
      ModelAndView modelAndView) throws Exception {}
   
   @Override
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
      Object handler, Exception exception) throws Exception {}
}

سوف تضطر إلى تسجيل هذا المعترض مع InterceptorRegistry باستخدام WebMvcConfigurerAdapter كما هو موضح أدناه -

@Component
public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
   @Autowired
   ProductServiceInterceptor productServiceInterceptor;

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
      registry.addInterceptor(productServiceInterceptor);
   }
}
في المثال الوارد أدناه ، سنصل إلى واجهة برمجة تطبيقات منتجات GET التي تعطي الناتج كما هو موضح أدناه -

 يتم إعطاء رمز فئة InterSoror ProductServiceInterceptor.java أدناه -

package com.ahmedalmahallawi.demo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
   @Override
   public boolean preHandle
      (HttpServletRequest request, HttpServletResponse response, Object handler) 
      throws Exception {
      
      System.out.println("Pre Handle method is Calling");
      return true;
   }
   @Override
   public void postHandle(HttpServletRequest request, HttpServletResponse response, 
      Object handler, ModelAndView modelAndView) throws Exception {
      
      System.out.println("Post Handle method is Calling");
   }
   @Override
   public void afterCompletion
      (HttpServletRequest request, HttpServletResponse response, Object 
      handler, Exception exception) throws Exception {
      
      System.out.println("Request and Response is completed");
   }
}
يتم توفير رمز فئة ملف تكوين التطبيق لتسجيل Interceptor في Interceptor Registry - ProductServiceInterceptorAppConfig.java أدناه -
package com.ahmedalmahallawi.demo.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Component
public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
   @Autowired
   ProductServiceInterceptor productServiceInterceptor;

   @Override
   public void addInterceptors(InterceptorRegistry registry) {
      registry.addInterceptor(productServiceInterceptor);
   }
}
ويرد رمز لملف فئة تحكم ProductServiceController.java أدناه -

package com.ahmedalmahallawi.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.tutorialspoint.demo.exception.ProductNotfoundException;
import com.tutorialspoint.demo.model.Product;

@RestController
public class ProductServiceController {
   private static Map<String, Product> productRepo = new HashMap<>();   
   static {      
      Product honey = new Product();
      honey.setId("1");
      honey.setName("Honey");
      productRepo.put(honey.getId(), honey);      
      Product almond = new Product();
      almond.setId("2");
      almond.setName("Almond");
      productRepo.put(almond.getId(), almond);      
   }
   @RequestMapping(value = "/products")
   public ResponseEntity<Object> getProduct() {
      return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
   }
}
ويرد رمز فئة POJO ل Product.java أدناه -
package com.ahmedalmahallawi.demo.model;

public class Product {
   private String id;
   private String name;

   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
فيما يلي رمز لملف فئة تطبيق Spring Boot الرئيسي DemoApplication.java -

package com.ahmedalmahallawi.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);   
   }
}
يظهر رمز Maven build - pom.xml هنا -
xml version = "1.0" encoding = "UTF-8"?>
 xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "
   http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   
   4.0.0
com.tutorialspoint demo 0.0.1-SNAPSHOT jar demo Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.5.8.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
يظهر رمز Gradle Build build.gradle هنا -

buildscript {
   ext {
      springBootVersion = '1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}
dependencies {
   compile('org.springframework.boot:spring-boot-starter-web')
   testCompile('org.springframework.boot:spring-boot-starter-test')
}

يمكنك إنشاء ملف JAR قابل للتنفيذ ، وتشغيل تطبيق Spring Boot باستخدام أوامر Maven أو Gradle أدناه.
 بالنسبة إلى Maven ، استخدم الأمر كما هو موضح أدناه -
mvn clean install
بعد "بناء النجاح" ، يمكنك العثور على ملف JAR ضمن الدليل الهدف.
 بالنسبة إلى Gradle ، استخدم الأمر كما هو موضح أدناه -
gradle clean build
بعد "BUILD SUCCESSFUL" ، يمكنك العثور على ملف JAR ضمن دليل build / libs.
 يمكنك تشغيل ملف JAR باستخدام الأمر التالي -
java –jar  
الآن ، بدأ التطبيق على منفذ Tomcat 8080 كما هو موضح أدناه.
الآن اضغط على الرابط أدناه في تطبيق POSTMAN ويمكنك أن ترى الإخراج كما هو موضح أدناه -

 الحصول على API: http: // localhost: 8080 / products