猿问

spring 从函数调用控制器方法

我有一个控制器:-


@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");代码不起作用。所以请建议一些方法来做到这一点。


繁华开满天机
浏览 109回答 1
1回答

MM们

作为最佳实践,您不应该真正将登录放在获取请求中。其次,如果您希望您的过滤器验证登录,您可以将它用作中间件/作为方面/或者只在服务类中编写验证方法并使用它。如果你真的想通过过滤器调用端点,你可以尝试使用 rest 模板。String fooResourceUrl = "http://localhost:8080/user/login";User userWithLoginCredentials = new User() //Create your user objectHttpEntity<User> request = new HttpEntity<>(userWithLoginCredentials);RestTemplate restTemplate = new RestTemplate();ResponseEntity<Foo> response = restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, User.class);
随时随地看视频慕课网APP

相关分类

Java
我要回答