任何人都可以帮我读取 Spring Boot 拦截器(preHandle方法)中的应用程序属性值吗?
我正在尝试在preHandle. 这个逻辑需要从application.properties文件中获取一些值。我使用@Value注释,但它始终为空。
谢谢
我已经实现了HttpInterceptor接口以拦截传出的请求和传入的响应。
我想在创建请求时显示加载程序,并在收到响应时隐藏该加载程序。
虽然下面的代码在检测到 HttpResponse 时工作,但它不会检测到 Http Failure(当响应代码不同于 200 时),因此,加载器不会被隐藏。
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private loaderService: LoaderService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loaderService.show();
return next
.handle(req)
.do(event => {
//nothing is printed when a Http failure occurs
console.log('detecting event ', event);
if (event instanceof HttpResponse) {
console.log('detecting http response');
this.loaderService.hide();
}
});
}
}
Run Code Online (Sandbox Code Playgroud) 我构建了一个 Angular 5 应用程序,它在我每次调用时处理错误。使用 HttpClient 我能够拦截在向服务器发送请求后发生的错误。错误在将请求发送到 API 的服务方法上被拦截,然后当发生错误时,它会被推送到组件以显示带有错误消息的漂亮模式。
我想使用拦截器来实现相同的行为,以便以一种集中的方式处理所有错误。但是我不确定是否可以从拦截器类与组件进行通信,将消息发送给它,以便它可以像当前那样触发模态,或者如何直接从拦截器类触发模态。
这是我目前的逻辑:
组件:
....
export class VerificationComponent implements OnInit {
//Use to call the modal when errors happen
@ViewChild('modalError') displayErrorRef: ModalComponent;
//Method send a request to the api using a service instance _myService
getNextRecord() {
this.errorMesage = "";
this._myService.getCandidate()
.subscribe(candidate => {
this.loadCandidate = candidate;
this.userName = this.appService.getUser();
}, error => {
this.errorMesage = <any>error.errorMessage;
this.displayErrorRef.show();
});
}
}
....
Run Code Online (Sandbox Code Playgroud)
服务:
.....
@Injectable()
export class MyService {
getCandidate(): Observable<ICandidate> {
return this._http.get(this._getCandidateUrl, …Run Code Online (Sandbox Code Playgroud) 我使用 ngx-translator 进行本地化。当我尝试读取本地化存储在本地文件夹中的 json 文件时,我收到错误 HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http:/host.com/api/资产/i18n/en.json”,好的:假,...}。我认为问题出在我在应用程序中使用的拦截器中。
// app.module.ts
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}
Run Code Online (Sandbox Code Playgroud)
如何在此功能中禁用拦截器?我试图将标头设置为 X-Skip-Interceptor,但它没有帮助。
localization interceptor angular-http-interceptors ngx-translate angular
当很少有参数不满足时,我试图从 Retrofit 拦截器显示一个对话框。但是android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?在尝试显示对话框时出现异常。
这是我的代码。
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(ShieldSquare.applicationContext)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure to Exit")
.setMessage("Exiting will call finish() method")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
//set negative button
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what should happen when negative button is clicked
Toast.makeText(ShieldSquare.applicationContext,
"Nothing Happened", Toast.LENGTH_LONG).show(); …Run Code Online (Sandbox Code Playgroud) 在我的应用程序中,身份验证基于 JWT 令牌。为了使它们无效,我在 JWT 中放置了一个随机安全字符串,并在数据库中放置了与拥有令牌的用户相关联的完全相同的字符串。这两个必须匹配才能使 JWT 有效。当用户注销时,API 会生成另一个随机字符串并替换数据库中的旧字符串,从而使 JWT 对该用户无效,因为 de JWT 中的字符串与数据库的字符串不匹配。
为此,我需要一个拦截器,在对 API 的每个请求之前发出一个静默请求,以检查随机字符串是否相等。基于这个问题,我的拦截器工作但行为怪异,发出无限请求并抛出“递归过多”错误。
我究竟做错了什么?
拦截器
import { TokenService } from './token.service';
import { Router } from '@angular/router';
import { HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent,
HttpClient,
HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { SharedService } from "./shared-service.service";
import { CookieService } from 'ngx-cookie-service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private sharedService : SharedService,
private httpClient …Run Code Online (Sandbox Code Playgroud) 我目前正在编写某种框架,允许其他人为它编写 REST 控制器。自然地,我希望那些“其他人”与我的代码中发生的事情有尽可能少的互动。
具体来说,我想要并且需要访问请求数据(即
RequestEntity在其余控制器处理请求之前。在控制器处理请求之前“拦截”请求,然后才让控制器处理它。
考虑以下代码:
@RestController
@RequestMapping("/")
public class MyController {
@GetMapping("/")
@ResponseBody
public ResponseEntity<String> getSomething(RequestEntity requestEntity) {
MyClass.doStuffWithRequestEntity(requestEntity);
// ...
Run Code Online (Sandbox Code Playgroud)
现在我需要的是ExternalClass.doStuffWithRequestEntity(requestEntity);在不需要明确调用它的情况下调用它。是否可以调用某个类中的某些方法(将 RequestEntity 传递给它!)而不必显式调用它?
此外,所述拦截器类应该创建和配置一个对象,然后该对象再次可供其余控制器使用。
我会想像
class RestController {
@RestController
@RequestMapping("/")
public class MyController {
@GetMapping("/")
@ResponseBody
public ResponseEntity<String> getSomething() {
MyClass x = MyClass.getInstanceCreatedByInterceptor();
}
}
}
Run Code Online (Sandbox Code Playgroud)
和
class Interceptor {
public void doStuffWithRequestEntity(requestEntity) {
MyClass x = new MyClass();
x.fillObjectWithData();
}
}
Run Code Online (Sandbox Code Playgroud)
之前被执行。
这个想法是解析每个(!)传入的请求并对其内容进行解码,而其余控制器的程序员根本不必关心这一点。他们应该只通过/从 MyClass 实例访问数据。
有没有办法做到这一点?
我知道这就是拦截器的工作方式,来自应用程序的请求通过 OkHttp 核心,通过改造包装器和 OkHttpp 核心调用来发出实际的网络请求,并通过改造包装器对应用程序拦截器响应进行网络响应。
有没有办法避免从应用程序拦截器调用实际请求,例如,在应用程序拦截器的某些场景中,检查请求 URL 是否是某个字符串,然后,在这种情况下,不要调用实际的网络请求并直接从应用程序拦截器返回硬编码的响应?
我已经知道我们可以从下面的代码创建全局拦截器:
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LoggingInterceptor,
},
],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)
来源:文档
但是,如果我想说,UserInterceptor.
UserInterceptor将从数据库中获取用户并转换请求。
UserInterceptor需要注入让说UserService。
我想在UserInterceptor全球范围内使用。
@Injectable()
export class UserInterceptor {
constructor(private readonly service: UserService) {}
}
Run Code Online (Sandbox Code Playgroud)
从文档中,我们不能这样做,app.useGlobalInterceptors(new UserInterceptor())因为UserInterceptor在构造函数 (UserService) 中需要 1 个参数。
而且由于我们使用了APP_INTERCEPTORfor LoggingInterceptor,我没有找到另一种方法来分配另一个值来APP_INTERCEPTOR全局使用拦截器。
例如,我认为如果我们可以这样做,问题就会解决:
providers: [
{
provide: APP_INTERCEPTOR,
useClass: [LoggingInterceptor, …Run Code Online (Sandbox Code Playgroud) interceptor ×10
angular ×3
android ×2
httpclient ×2
nestjs ×2
retrofit ×2
spring ×2
typescript ×2
angular5 ×1
dialog ×1
http ×1
javascript ×1
loader ×1
localization ×1
node.js ×1
okhttp ×1
request ×1
spring-boot ×1
web ×1