春季拦截不起作用

时间:2017-01-22 18:39:00

标签: java angularjs spring interceptor

我知道这已被问过很多次,但是没有一个可以使我的代码工作。我可能做错了什么但我无法找到答案。

我使用Spring Boot与AngularJS,我试图做的是预先处理所有请求。

这是我的代码:

控制器:

@RestController
@RequestMapping(value = { "/user" })
public class UserController {

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public String getLanguage() {
        return "user";
    }
}

拦截器:

@Component
public class RequestHandler extends HandlerInterceptorAdapter {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
      System.out.println("intercepted");
      return false;
  }
}

WebConfig:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

  @Autowired
  HandlerInterceptor requestHandler;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(requestHandler);
  }
}

我将其添加到applicationContext.xml:

<mvc:interceptors>
    <bean class="server.RequestHandler" />
</mvc:interceptors>

我整个周末都在尝试做这项工作而且我无法提供任何帮助,我们将非常感激!

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试手动定义<?xml version="1.0" encoding="UTF-8"?> <ejb-jar xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd" version="3.2"> <enterprise-beans> <session> <ejb-name>MyLiquibaseRunnerBean</ejb-name> <ejb-class>com.example.MyLiquibaseRunnerBean</ejb-class> <transaction-type>Bean</transaction-type> </session> </enterprise-beans> </ejb-jar> ,而不会将Bean声称为Interceptor,如下所示:

RequestHandler.java

@Component

WebConfig.java

public class RequestHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws ServletException {
        System.out.println("intercepted");
        return true;
    }
}

顺便说一句:如果将类声明为拦截器,为什么不将它重命名为包含术语 Interceptor 的内容,例如@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Bean public RequestHandler requestHandler() { return new RequestHandler(); } @Override public void addInterceptors(final InterceptorRegistry registry) { registry.addInterceptor(requestHandler()); } }

它应该直截了当。请告诉我这是否适合您!

更新:我已经在原型中实现了这一点。请参阅此最小,完整且可验证的示例。希望能帮助到你! https://github.com/dbubenheim/stackoverflow-41794738.git