2016-07-07 4 views
9

Я столкнулся с пружинной загрузкой и намерен добавить цепочку фильтров для входящего запроса.Как настроить цепочку фильтров в весеннем ботинке?

Вот Применение:

package example.hello; 

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.context.ApplicationContext; 

@SpringBootApplication 
public class Application { 

    public static void main(String[] args) { 
     ApplicationContext ctx = SpringApplication.run(Application.class, args); 
    } 

} 

Вот контроллер:

package example.hello; 

import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.bind.annotation.RestController; 

import java.util.concurrent.atomic.AtomicLong; 

@RestController 
public class GreetingController { 

    private static final String template = "Hello, %s!"; 
    private final AtomicLong counter = new AtomicLong(); 

    @RequestMapping("/greeting") 
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { 
     return new Greeting(counter.incrementAndGet(), 
       String.format(template, name)); 
    } 
} 

Вот Filter Config:

package example.hello; 

import org.springframework.boot.context.embedded.FilterRegistrationBean; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 

@Configuration 
public class WebConfig { 

    @Bean 
    public FilterRegistrationBean greetingFilterRegistrationBean() { 
     FilterRegistrationBean registrationBean = new FilterRegistrationBean(); 
     registrationBean.setName("greeting"); 
     GreetingFilter greetingFilter = new GreetingFilter(); 
     registrationBean.setFilter(greetingFilter); 
     registrationBean.setOrder(1); 
     return registrationBean; 
    } 

    @Bean 
    public FilterRegistrationBean helloFilterRegistrationBean() { 
     FilterRegistrationBean registrationBean = new FilterRegistrationBean(); 
     registrationBean.setName("hello"); 
     HelloFilter helloFilter = new HelloFilter(); 
     registrationBean.setFilter(helloFilter); 
     registrationBean.setOrder(2); 
     return registrationBean; 
    } 

} 

Вот HelloFilter и поздравительных Фильтр:

package example.hello; 

import javax.servlet.*; 
import java.io.IOException; 

public class HelloFilter implements Filter { 
    @Override 
    public void init(FilterConfig filterConfig) throws ServletException { 

    } 

    @Override 
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 
     System.out.println("HelloFilter!"); 
    } 

    @Override 
    public void destroy() { 

    } 
} 

package example.hello; 

import javax.servlet.*; 
import java.io.IOException; 

public class GreetingFilter implements Filter { 
    @Override 
    public void init(FilterConfig filterConfig) throws ServletException { 

    } 

    @Override 
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 
     System.out.println("Greetings from filter!"); 
    } 

    @Override 
    public void destroy() { 

    } 
} 

Когда я запускаю приложение и запускаю curl localhost:8080/greeting, принимается только «Приветствия из фильтра», а HelloFilter не вызывается.

Кроме того, нет ответа от Greeting Controller. Кажется, что GreetingFilter блокирует процедуру.

Итак, как установить цепочку фильтров весной. Есть ли ошибки в коде выше?

+5

Ваш код испорчен ... Вы останавливаете/блокируете запрос на первом фильтре, который он никогда не пройдет. Вам нужно вызвать 'filterChain.doFilter (запрос, ответ)' для продолжения вызова ... –

ответ

8

Добавление следующей строки кода в GreetingFilter работает

filterChain.doFilter(servletRequest, servletResponse); 
1

Я хотел бы уточнить немного больше о том, что предложил Gangadhar. Вы можете попробовать:

filterChain.doFilter (servletRequest, servletResponse);

in doFilter метод ваших классов фильтров. Это создаст цепочку фильтров.