如何为 Spring RESTful Web 服务创建 Spring Interceptor [英] How to create a Spring Interceptor for Spring RESTful web services

查看:31
本文介绍了如何为 Spring RESTful Web 服务创建 Spring Interceptor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些没有 web.xml 的 Spring RESTful (RestControllers) web 服务,我使用 Spring boot 来启动这些服务.

I have some Spring RESTful (RestControllers) web services with no web.xml and I am using Spring boot to start the services.

我想为 Web 服务添加授权层,并希望在实际调用 Web 服务本身之前将所有 http 请求路由到一个前端控制器.(我有一个代码来模拟身份验证层的会话行为,根据我与客户端的每个 httpRequest 一起发送的生成的密钥来验证用户).

I want to add authorization layer for the web services and wanted to route all the http requests to one front controller before actually calling the web service itself. (I have a code to simulate sessions behavior at the autherisation layer, to validate a user based on a generated key that I send with each of the httpRequest from the client).

是否有将所有请求路由到过滤器/前端控制器的标准 Spring 解决方案?

Is there any Standard Spring solution on routing all the requests to a filter /front controller?

提前致谢,普拉尼斯

添加我的代码

控制器:`

@RestController
public class UserService {
    UserDAO userDAO = new UserDAO();

    @RequestMapping(value="/login", method = RequestMethod.POST)
    @LoginRequired
    public String login(@RequestParam(value="user_name") String userName, @RequestParam(value="password") String password, HttpServletRequest request){
        return userDAO.login(userName, password);
    }
}`

拦截器:

`

public class AuthenticationInterceptor implements HandlerInterceptor  {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        System.out.println("In Interceptor");
        //return super.preHandle(request, response, handler);
        return true;
    }
    @Override
    public void postHandle( HttpServletRequest request, HttpServletResponse response,
            Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("---method executed---");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) throws Exception {
        System.out.println("---Request Completed---");
    }
}

`

界面.`

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}

`

推荐答案

使用 Spring 实现拦截器可以采取以下步骤:

Following steps can be taken to implement the interceptor with Spring:

  • 实现一个扩展 HandlerInterceptorAdapter 类的拦截器类.以下是代码的样子:

  • Implement an interceptor class extending HandlerInterceptorAdapter class. Following is how the code could look like:

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception)
    throws Exception {
    // TODO Auto-generated method stub

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
    throws Exception {
    // TODO Auto-generated method stub

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        String emailAddress = request.getParameter("emailaddress");
        String password = request.getParameter("password");

        if(StringUtils.isEmpty(emailAddress) || StringUtils.containsWhitespace(emailAddress) ||
        StringUtils.isEmpty(password) || StringUtils.containsWhitespace(password)) {
            throw new Exception("Invalid User Id or Password. Please try again.");
        }

        return true;
    }


}

  • 实现 AppConfig 类或在现有配置类之一中添加 addInterceptors.注意 LoginInterceptor 实例指定的路径模式

  • Implement an AppConfig class or add the addInterceptors in one of the existing Configuration class. Note the path pattern specified with the LoginInterceptor instance

    @Configuration  
    public class AppConfig extends WebMvcConfigurerAdapter  {  
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
           registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/account/login");
        }
    } 
    

  • 实现控制器方法如下:

  • Implement the controller method such as following:

    @Controller
    @RequestMapping("/account/login")
    public class LoginController {
    
        @RequestMapping(method = RequestMethod.GET)
        public String login() {
            return "login";
        }
    }
    

  • 这篇关于如何为 Spring RESTful Web 服务创建 Spring Interceptor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆