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

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

spring 從函數調用控制器方法

spring 從函數調用控制器方法

繁華開滿天機 2023-06-08 20:58:17
我有一個控制器:-@CrossOrigin(origins = "http://localhost", maxAge = 3600)@RestController@RequestMapping("/user")public class UserController {  @RequestMapping(value = "/login", method = RequestMethod.get)    public String login(@RequestBody User login) throws ServletException{  }}我還有另一GenericFilterBean堂課。這是為了執行一些安全功能,例如驗證令牌等。public class JwtFilter extends GenericFilterBean {    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)            throws IOException, ServletException {     final HttpServletRequest request = (HttpServletRequest) req;    final HttpServletResponse response = (HttpServletResponse) res;    final String authHeader = request.getHeader("authorization");    if ("OPTIONS".equals(request.getMethod())) {        response.setStatus(HttpServletResponse.SC_OK);        chain.doFilter(req, res);    } else {        if (authHeader == null || !authHeader.startsWith("Bearer ")) {            new ModelAndView("user/login");// this way i am trying to call one controller method.             throw new ServletException("Missing or invalid Authorization header"); // this is throws one exception. This is only for the dev purpose.        }else {            final String token = authHeader.substring(7);            try {                final Claims claims = Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody();                request.setAttribute("claims", claims);            } catch (final SignatureException e) {                throw new ServletException("Invalid token");            }            chain.doFilter(req, res);        }    }   }}我的問題來自于doFilter我如何調用控制器方法的方法login此new ModelAndView("user/login");代碼不起作用。所以請建議一些方法來做到這一點。
查看完整描述

1 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

作為最佳實踐,您不應該真正將登錄放在獲取請求中。


其次,如果您希望您的過濾器驗證登錄,您可以將它用作中間件/作為方面/或者只在服務類中編寫驗證方法并使用它。


如果你真的想通過過濾器調用端點,你可以嘗試使用 rest 模板。


String fooResourceUrl = "http://localhost:8080/user/login";

User userWithLoginCredentials = new User() //Create your user object

HttpEntity<User> request = new HttpEntity<>(userWithLoginCredentials);

RestTemplate restTemplate = new RestTemplate();

ResponseEntity<Foo> response = restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, User.class);

查看完整回答
反對 回復 2023-06-08
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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