springMVC 过滤器获取bean 和 multipart/form-data请求参数

在web项目中,有时我们需要在自定义的过滤器中对请求进行身份验证或者其他一些操作,这里就可能出现一些问题,如获取不到multipart/form-data请求参数,无法注入bean等。
这里介绍其中一种简单的解决方案:

  • 过滤器中获取bean
    可以通过spring上下文实现,主要操作是:
	ServletContext sc = filterConfig.getServletContext();
    XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);
    DemoBean demoBean = (DemoBean) cxt.getBean("demoBean");
  • 获取 multipart/form-data 请求参数
    可通过CommonsMultipartResolver 类的resolveMultipart(final HttpServletRequest request)方法将HttpServletRequest转化为MultipartHttpServletRequest,然后通过MultipartHttpServletRequest对象的getParameter(String var1)方法获取对应的属性值。
	String contentType = request.getContentType();
    if (contentType != null && contentType.contains("multipart/form-data")) {
		MultipartHttpServletRequest multiReq = multipartResolver.resolveMultipart(request);
	}
	String var = request.getParameter("var");
  • 总结
    1、web.xml 配置
 <filter>
    <filter-name>myFilterfilter-name>
    <filter-class>com.xiaoli.web.filter.MyFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>myFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

如果一个过滤器要配置多个url-pattern,请配置多个filter-mapping,如下:

 <filter>
    <filter-name>myFilterfilter-name>
    <filter-class>com.xiaoli.web.filter.MyFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>myFilterfilter-name>
    <url-pattern>/pattern1/*url-pattern>
  filter-mapping>
  <filter-mapping>
    <filter-name>myFilterfilter-name>
    <url-pattern>/pattern2/*url-pattern>
  filter-mapping>

2、自定义过滤器 MyFilter.java

	public class MyFilter implements Filter {
    private CommonsMultipartResolver multipartResolver;
    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        multipartResolver = new CommonsMultipartResolver();
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 获取bean
        ServletContext sc = filterConfig.getServletContext();
        XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);
        DemoBean demoBean = (DemoBean) cxt.getBean("demoBean");
		// 处理 multipart/form-data 请求
		String contentType = request.getContentType();
        if (contentType != null && contentType.contains("multipart/form-data")) {
	        MultipartHttpServletRequest multiReq = multipartResolver.resolveMultipart(request);
	        // 将转化后的 request 放入过滤链中
            servletRequest = multiReq;
            request = multiReq;
        }
	    //todo : your code
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {}

}

你可能感兴趣的:(spring)