For example, if you want to implement the logic that check the request whether this request is accepted by log in, session or authentication header,
you can implement that by using interceptor,and applying that by url pattern.
You can find the source code as below.
- Structure
package org.blog.test; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }
- HelloInterceptor.java
package org.blog.test.component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; @Component @Slf4j public class HelloInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("interceptor intercept request"); response.addHeader("interceptor-header", "interceptor added"); return true; } }
- WebConfig.java
package org.blog.test.configuration; import org.blog.test.component.HelloInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class Webconfig extends WebMvcConfigurerAdapter { @Autowired private HelloInterceptor helloInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(helloInterceptor).addPathPatterns("/hello/**"); } }
- HelloController.java
package org.blog.test.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping(value = "/hello", method = RequestMethod.GET) public String getHello() { return "hello"; } @RequestMapping(value = "/bye", method = RequestMethod.GET) public String getbye() { return "bye"; } }
- pom.xml
4.0.0 org.blog.test interceptor-test 0.1.0 org.springframework.boot spring-boot-starter-parent 1.3.2.RELEASE org.springframework.boot spring-boot-starter-web org.projectlombok lombok 1.16.6
- Execution Result
You can find the result that when /hello was called, "interceptor-header: interceptor added" was added as header,
and /bye was called, that is not.
댓글 없음 :
댓글 쓰기