拦截器

-


interceptor

  • Before sending the request to the controller
  • Before sending the response to the client
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.yoozoo.mba.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yoozoo.mba.config.AppConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class YoobiCookieInterceptor implements HandlerInterceptor {

@Autowired
AppConfig appConfig;

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

Cookie[] cookies = request.getCookies();
String cookieValue = null;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("JSESSIONID")) {
cookieValue = cookie.getValue();
break;
}
}
}

appConfig.setJSESSIONID(cookieValue);

return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception exception) throws Exception {
}
}

register this Interceptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.yoozoo.mba.config;

import com.yoozoo.mba.interceptor.YoobiCookieInterceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
YoobiCookieInterceptor yoobiCookieInterceptor;

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

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×