如何从 HttpInterceptor 为 Controller 设置变量?
How to set a variable for Controller from HttpInterceptor?
我正在构建一个 Spring 引导应用程序。
我喜欢为 Spring 启动应用程序设置一个变量。此变量应在 HTTP 拦截器中设置。我这样做的原因是,这个变量将存储一些 ID,并且这个 ID 将在每个控制器的方法中使用。
我怎样才能做到这一点?
- 将其作为 JVM 参数传递并使用 System.getProperty。
- 使用 -Dspring-boot.run.arguments=--interceptor.enabled=true 并在 application.properties 中保留备份配置或使用 -Drun.arguments 并访问属性 键直接在你的拦截器中
您在 HTTP 拦截器中设置了变量?
所以它不是唯一的全局变量,它是每个请求都不同的ID?这就是请求属性的用途:
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if(request.getMethod().matches(RequestMethod.OPTIONS.name())) {
return true;
}
request.setAttribute("MY_ID", generateId(...));
return true;
}
}
@Controller
public class SampleController {
@RequestMapping(...)
public String something(HttpServletRequest req, HttpServletResponse res){
System.out.println( req.getAttribute("MY_ID"));
}
}
我正在构建一个 Spring 引导应用程序。
我喜欢为 Spring 启动应用程序设置一个变量。此变量应在 HTTP 拦截器中设置。我这样做的原因是,这个变量将存储一些 ID,并且这个 ID 将在每个控制器的方法中使用。
我怎样才能做到这一点?
- 将其作为 JVM 参数传递并使用 System.getProperty。
- 使用 -Dspring-boot.run.arguments=--interceptor.enabled=true 并在 application.properties 中保留备份配置或使用 -Drun.arguments 并访问属性 键直接在你的拦截器中
您在 HTTP 拦截器中设置了变量? 所以它不是唯一的全局变量,它是每个请求都不同的ID?这就是请求属性的用途:
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if(request.getMethod().matches(RequestMethod.OPTIONS.name())) {
return true;
}
request.setAttribute("MY_ID", generateId(...));
return true;
}
}
@Controller
public class SampleController {
@RequestMapping(...)
public String something(HttpServletRequest req, HttpServletResponse res){
System.out.println( req.getAttribute("MY_ID"));
}
}