1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springmodules.validation.bean.context.web;
18
19 import java.beans.PropertyEditorManager;
20
21 import javax.servlet.http.HttpServletRequest;
22 import javax.servlet.http.HttpServletResponse;
23
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.springframework.util.AntPathMatcher;
27 import org.springframework.util.PathMatcher;
28 import org.springframework.web.servlet.ModelAndView;
29 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
30 import org.springmodules.validation.bean.context.ValidationContextUtils;
31
32
33
34
35
36
37
38 public class ValidationContextHandlerInterceptor extends HandlerInterceptorAdapter {
39
40 private final static Logger logger = LoggerFactory.getLogger(ValidationContextHandlerInterceptor.class);
41
42 static {
43 PropertyEditorManager.registerEditor(ValidationContextUrlMapping[].class,
44 ValidationContextUrlMappingArrayPropertyEditor.class);
45 }
46
47 private ValidationContextUrlMapping[] validationContextUrlMappings;
48
49 private PathMatcher pathMatcher;
50
51 public ValidationContextHandlerInterceptor() {
52 validationContextUrlMappings = new ValidationContextUrlMapping[0];
53 pathMatcher = new AntPathMatcher();
54 }
55
56
57
58
59
60
61
62
63 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
64
65 String[] contextTokens = new String[0];
66
67 for (int i=0; i<validationContextUrlMappings.length; i++) {
68 String pattern = validationContextUrlMappings[i].getUrlPattern();
69 if (pathMatcher.match(pattern, request.getRequestURI())) {
70 contextTokens = validationContextUrlMappings[i].getContextTokens();
71 break;
72 }
73 }
74
75 if (logger.isInfoEnabled() && contextTokens.length == 0) {
76 logger.info("No validation context url mapping matches url '" + request.getRequestURI() +
77 "'. Setting validation context without supported tokens...");
78 }
79
80 ValidationContextUtils.setContext(contextTokens);
81
82
83 return true;
84 }
85
86
87
88
89
90
91
92
93
94 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
95 ValidationContextUtils.clearContext();
96 }
97
98
99
100
101 public ValidationContextUrlMapping[] getValidationContextUrlMappings() {
102 return validationContextUrlMappings;
103 }
104
105 public void setValidationContextUrlMappings(ValidationContextUrlMapping[] validationContextUrlMappings) {
106 this.validationContextUrlMappings = validationContextUrlMappings;
107 }
108
109 public PathMatcher getPathMatcher() {
110 return pathMatcher;
111 }
112
113 public void setPathMatcher(PathMatcher pathMatcher) {
114 this.pathMatcher = pathMatcher;
115 }
116
117 }