亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Spring - 在調用控制器的方法之前執行代碼

Spring - 在調用控制器的方法之前執行代碼

米琪卡哇伊 2022-05-21 20:19:00
在調用控制器中的方法之前,是否有任何類似于@PreAuthorize或@PreFilter我可以用來運行代碼的注釋?我需要將信息添加到請求上下文(特定于被調用的方法),然后由ExceptionHandler.例如@RestControllerpublic MyController{  @UnkwonwAnnotation("prepareContext(request.getAgentId())"){  public ResponseEntity method1(RequestA requestA) {    ...  }  @UnkwonwAnnotation("prepareContext(request.getUserName())"){  public ResponseEntity method1(RequestB requestB) {    ...  }}我實際上可以使用@PreAuthorize但感覺不對
查看完整描述

3 回答

?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

您可以為此添加攔截器


樣本攔截器


public class CustomInterceptor implements HandlerInterceptor {


    

    @Override

    public boolean preHandle(HttpServletRequest request,HttpServletResponse  response) {

    //Add Login here 

        return true;

    }

配置


@Configuration

public class MyConfig extends WebMvcConfigurerAdapter {

    @Override

    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new MyCustomInterceptor()).addPathPatterns("/**");

    }

}

希望這可以幫助


查看完整回答
反對 回復 2022-05-21
?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

也許一個不錯的選擇是實現一個自定義過濾器,該過濾器在每次收到請求時運行。


您需要擴展“OncePerRequestFilter”并覆蓋方法“doFilterInternal”


public class CustomFilter extends OncePerRequestFilter {


    @Override

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,

                                    FilterChain filterChain) throws ServletException, IOException {


        //Add attributes to request

        request.getSession().setAttribute("attrName", new String("myValue"));


        // Run the method requested by petition

        filterChain.doFilter(request, response);


        //Do something after method runs if you need.


    }

}

在您必須在 Spring 中使用 FilterRegistrationBean 注冊過濾器之后。如果你有 Spring 安全,你需要在安全過濾器之后添加你的過濾器。


查看完整回答
反對 回復 2022-05-21
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

Spring Aspect 也是在控制器之前執行代碼的好選擇。


@Component

@Aspect

public class TestAspect {


    @Before("execution(* com.test.myMethod(..)))")

    public void doSomethingBefore(JoinPoint jp) throws Exception {


        //code  

    }

}

這里myMethod()將在控制器之前執行。


查看完整回答
反對 回復 2022-05-21
  • 3 回答
  • 0 關注
  • 212 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號