有谁知道如何使用Spring MVC拦截器更改发布的值?我看到了一些例子,但没有关于这个主题的例子.我知道如何获得它们,但我不知道如何对其进行修改.
@Component
public class CultureInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
// we get the posted values
String culture = request.getParameter("culture");
String a = request.getParameter("a");
String b = request.getParameter("b");
System.out.println(String.format("[CultureInterceptor culture=%s, a=%s, b=%s]", culture, a, b));
if (culture != null && a != null && b != null && "fr-FR".equals(culture)) {
a = a.replace(",", ".");
b = b.replace(",", ".");
}
System.out.println(String.format("[CultureInterceptor culture=%s, a=%s, b=%s]", culture, a, b));
return true;
}
上面,我创建了已发布值[a]和[b]的副本,但未在请求中修改它们.有什么想法吗?
解决方法:
我回答我自己的问题.实际上,这相当复杂,我花了一些时间才能找到可行的解决方案.
首先,我在Spring配置类(正是Spring Boot环境)中创建了一个过滤器:
@Configuration
@ComponentScan({ "istia.st.springmvc.config", "istia.st.springmvc.controllers", "istia.st.springmvc.models" })
@EnableAutoConfiguration
public class Config extends WebMvcConfigurerAdapter {
@Bean
public Filter cultureFilter() {
return new CultureFilter();
}
}
在这里,我们声明了一个过滤器(默认情况下),它将在到达最终处理程序之前过滤每个请求.然后我创建了过滤器:
public class CultureFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// next handler
filterChain.doFilter(new CultureRequestWrapper(request), response);
}
}
[OncePerRequestFilter]是一个Spring类.技巧是用一个新的[CultureRequestWrapper(request)]替换实际的请求.然后,我创建了CultureRequestWrapper:
public class CultureRequestWrapper extends HttpServletRequestWrapper {
public CultureRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String[] getParameterValues(String name) {
// posted values a et b
if (name != null && (name.equals("a") || name.equals("b"))) {
String[] values = super.getParameterValues(name);
String[] newValues = values.clone();
newValues[0] = newValues[0].replace(",", ".");
return newValues;
}
// other cases
return super.getParameterValues(name);
}
}
我重新定义了[HttpServletRequest]的[getParameterValues],但这取决于将管理请求的最终servlet.我们必须重新定义
此servlet使用的[HttpServletRequest]方法.