我有一个带模块的EAR:
在foo-api中有:
@Local
FooService // (interface of a local stateless session bean)
Run Code Online (Sandbox Code Playgroud)
在foo-impl中有:
@Stateless
FooServiceImpl implements FooService //(implementation of the foo service)
Run Code Online (Sandbox Code Playgroud)
在interceptor.jar我想要
public class BazInterceptor {
@EJB
private FooService foo;
@AroundInvoke
public Object intercept( final InvocationContext i) throws Exception {
// do someting with foo service
return i.proceed();
}
Run Code Online (Sandbox Code Playgroud)
问题是:
Java EE 5兼容的应用程序服务器(例如JBoss 5)是否会注入拦截器?如果不是,访问会话bean的好策略是什么?
考虑:
假设我有一个存储库,它返回一个Posts 列表.存储库接口有一个GetAll()方法可以完成它的建议.
现在按照我不应该将域逻辑放在存储库中的理论,我想拦截对具体GetAll()方法的调用,以便我可以在GetAll()结果中添加以下逻辑:
return GetAll().OrderByDescending(p => p.Posted).ToList();
Run Code Online (Sandbox Code Playgroud)
我想拦截这个的原因是因为(1)我不想让客户端记得调用扩展方法(OrderByDescending或者一些无用的包装器),我想每次调用它,(2)我不我想让我所有的具体实现都记住订购GetAll()结果 - 我想把这个逻辑放在任何存储库外部的一个地方.
最简单的方法是什么?
我已经在使用StructureMap,所以如果我可以拦截它,它可能是一个低成本选项.但我不认为SM拦截方法调用,只是创建对象实例?
我需要转到代理还是混合模式?我是否需要使用Castle Dynamic Proxy全押?或者是否有其他方法我应该考虑或者可能是一种组合?
我真的对上面我特定例子的具体建议感兴趣.我是AOP的新手所以请保持温柔.
我正在使用JBoss 7.1构建Java EE应用程序.
为了对用户操作进行全面审核,我计划使用Interceptor来记录我的bean方法的每次调用.
为此,我有以下招标:
@Inherited
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Logged {
}
Run Code Online (Sandbox Code Playgroud)
然后我定义我的拦截器类:
@Logged
@Interceptor
public class UserActionInterceptor implements Serializable {
private static final long serialVersionUID = 1L;
private Logger log = LoggerFactory.getLogger(UserActionInterceptor.class);
public UserActionInterceptor() {
}
@AroundInvoke
public Object logMethodEntry(InvocationContext invocationContext) throws Exception {
log.debug(invocationContext.getMethod().getName() + " invoked.");
return invocationContext.proceed();
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,这工作正常.如果我使用这个拦截器绑定一个类,我会得到一些日志记录.但是,当我想要定位我的bean类时,它变得更加棘手.
如果我有一个@RequestScoped类型的bean并将其绑定到我的拦截器,它就可以工作.但是,如果我有一个@ViewScoped类型的bean,那么它不会.
我查了@ViewScoped的定义,发现:
@Retention(value=RUNTIME)
@Target(value=TYPE)
@Inherited
public @interface ViewScoped
Run Code Online (Sandbox Code Playgroud)
我觉得问题在于这个注释没有目标类型METHOD,它阻止我的拦截器拦截对类方法的调用.
以前有人有同样的问题吗?有人知道是否可以扩展bean的范围,以便可以截获其方法而不改变@ViewScoped的性质?
所以我有下面的场景来实现使用Spring boot rest template消费REST-API(涉及令牌认证机制)。为了执行测试,我在 Spring Boot 中创建了简单的模拟 REST API。这是过程,
从我的 API 消费者应用程序中,
rest-template受保护的 API发送请求,此 API 要求Authorization: Bearer <token>请求中存在标头。HTTP-Unauthorized (401).Authorization: Basic <token>存在标头。新的访问令牌将存储在静态字段中,并将用于所有其他请求进行身份验证。这可以通过简单的捕捉来实现401-HttpClientErrorException的RestTemplate消费方式(postForObject),但这个想法是从分离它REST-API的消费类。为了实现它,我尝试使用ClientHttpRequestInterceptor
这是我到目前为止尝试过的代码。
拦截器类
public class AuthRequestInterceptor implements ClientHttpRequestInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(AuthRequestInterceptor.class);
private static final String BASIC_AUTH_HEADER_PREFIX = "Basic ";
private static …Run Code Online (Sandbox Code Playgroud) 我试图弄清楚如何在 .NET 框架中执行之前拦截 GET 调用。
我创建了 2 个应用程序:一个前端(调用 API 并用它发送自定义 HTTP 标头)和一个后端 API:
前端调用API的方法:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:54857/";
string customerApi = "2";
using (var client = new HttpClient())
{
//get logged in userID
HttpContext context = System.Web.HttpContext.Current;
string sessionID = context.Session["userID"].ToString();
//Create request and add headers
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Custom header
client.DefaultRequestHeaders.Add("loggedInUser", sessionID);
//Response
HttpResponseMessage response = await client.GetAsync(customerApi);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json"); …Run Code Online (Sandbox Code Playgroud) 我使用 axios 拦截器来维护内部服务器错误。如果响应有错误而不重新加载,我需要重定向到另一个 url。下面的代码我使用了 location.href。所以它正在重新加载。我需要一个解决方案来重定向而不刷新页面。
我在 react-router-dom 中尝试了“重定向”。但它对我不起作用。
export function getAxiosInstance() {
const instance = axios.create();
const token = getJwtToken();
// Set the request authentication header
instance.defaults.headers.common['Authorization'] = `Bearer ${token}`;
// Set intercepters for response
instance.interceptors.response.use(
(response) => response,
(error) => {
if (config.statusCode.errorCodes.includes(error.response.status)) {
return window.location.href = '/internal-server-error';
}
return window.location.href = '/login';
}
);
return instance;
}
Run Code Online (Sandbox Code Playgroud)
谁能帮我解决这个问题?
我想知道是否有办法在 Angular 的 HttpInterceptor 中检索当前路由。我正在使用来自不同路线的相同拦截器,但我需要检查是否正在从特定路线使用拦截器。如果是这样,我想在执行之前向后端请求添加一个特定的标头。
似乎Route、Router、ActivatedRoute和ActivatedRouteSnapshot对此不起作用。
我目前使用windows.location作为临时解决方案,但想知道在 HttpRequest 拦截器中执行此操作的正确方法是什么。
我目前的代码:
@Injectable()
export class APIClientInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Check if the call is done from the embed route.
if (currentLocation.includes('/embed/')) {
// Get the hash ID.
const sIndex = currentLocation.lastIndexOf('/') + 1;
const sLength = currentLocation.length - sIndex;
const embedHash = currentLocation.substr(sIndex, sLength);
console.log(embedHash);
// Add the header to tell the …Run Code Online (Sandbox Code Playgroud) interceptor angular-routing angular-http-interceptors angular angular-router
我需要为我的 Spring Boot 应用程序创建一个 http 拦截器来检查请求的授权 Heather 是否有效,因此我进行了搜索,似乎可以使用 HandlerInterceptor 或 ClientHttpRequestInterceptor 来执行此操作。
在这种情况下,理想的拦截器是什么?我需要所有请求进行检查,如果未通过则拒绝访问,但对我来说,这两个拦截器似乎都做同样的事情,那么每个拦截器之间有什么区别?
重要细节:我使用 @RestController 来创建我的路由,如果该路由有特定的注释(如 @IgnoreAuthentication),那么拦截器将不需要检查身份验证。
我正在 NestJS 中编写 API,其中有一组通用标头。我决定使用拦截器将标头附加到传出请求中。标头不会附加到请求中,因此请求不断失败。
拦截器
import * as utils from '../utils/utils';
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor
} from '@nestjs/common';
import { HEADERS } from '../middlewares/headers.constant';
import { Observable } from 'rxjs';
import { Request } from 'express';
import { DATA_PARTITION_ID } from '../app.constants';
@Injectable()
export class HeadersInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<void> {
const ctx = context.switchToHttp();
const request: Request = ctx.getRequest();
this.setHeaders(request);
return next.handle();
}
private setHeaders(request): void {
this.updateHeaders(request, HEADERS.ACCEPT, 'application/json');
this.updateHeaders(request, HEADERS.CONTENT_TYPE, 'application/json'); …Run Code Online (Sandbox Code Playgroud) 我正在使用 Spring Boot 构建后端3.1.0-SNAPSHOT,它使用Spring Framework 6x.
拦截器:
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("preHandle");
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion");
}
}
Run Code Online (Sandbox Code Playgroud)
在之前的版本(Spring Boot 2)中,添加Interceptor的方式是:
@Configuration
public class AppConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor( new MyInterceptor());
}
}
Run Code Online (Sandbox Code Playgroud)
现在,添加此类配置类的正确方法是:
@Configuration
public class AppConfig {
// Not …Run Code Online (Sandbox Code Playgroud) interceptor ×10
java ×3
java-ee ×2
jboss ×2
spring ×2
spring-boot ×2
access-token ×1
angular ×1
aop ×1
api ×1
asp.net-mvc ×1
axios ×1
c# ×1
express ×1
handler ×1
http ×1
logging ×1
mixins ×1
nestjs ×1
node.js ×1
react-router ×1
reactjs ×1
resttemplate ×1
spring-mvc ×1
structuremap ×1
typescript ×1