拦截器与过滤器的区别以及如何自定义一个过滤器和拦截器

拦截器与过滤器的区别 :

     1. 拦截器是基于java的反射机制的,而过滤器是基于函数回调。
     2. 拦截器不依赖与servlet容器,过滤器依赖与servlet容器。
     3. 拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用。
     4. 拦截器可以访问action上下文、值栈里的对象,而过滤器不能访问。

     5. 在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次.


自定义一个拦截器(SpringMVC):

Spring MVC也可以使用拦截器对请求进行拦截处理,用户可以自定义拦截器来实现特定的功能,自定义的拦截器必须实现HandlerInterceptor接口。

代码如下:


  1.       
        import java.io.UnsupportedEncodingException;  
        import java.net.URLDecoder;  
        import java.util.Iterator;  
        import java.util.Map;  
          
        import javax.servlet.http.HttpServletRequest;  
          
        import org.apache.commons.logging.Log;  
        import org.apache.commons.logging.LogFactory;  
        import org.apache.struts2.ServletActionContext;  
          
        import com.opensymphony.xwork2.ActionInvocation;  
        import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  
           
        public class UrlDecodeFilterInterceptor extends AbstractInterceptor {  
            private static final long serialVersionUID = -2335290125344040914L;  
            private static final Log LOG = LogFactory.getLog(UrlDecodeFilterInterceptor.class);  
          
            public String intercept(ActionInvocation invocation) throws Exception {  
                Map parameters = invocation.getInvocationContext().getParameters();  
                HttpServletRequest request = ServletActionContext. getRequest();   
                  
                if("get".equalsIgnoreCase(request.getMethod())){  
                    for (Iterator i = parameters.keySet().iterator(); i.hasNext();) {  
                        String param = (String) i.next();  
                        String[] values = (String[])parameters.get(param);  
                        if(values != null && values.length > 0){  
                            for (int j = 0; j < values.length; j++) {  
                                if(values[j] != null && !"".equals(values[j])){  
                                    try {  
                                        values[j] = new String(values[j].getBytes("iso8859-1"),"UTF-8");  
                                        parameters.put(param, values[j]);  
                                    } catch (UnsupportedEncodingException e1) {  
                                        e1.printStackTrace();  
                                    }   
                                }  
                            }  
                        }  
                    }  
                }  
                  
                if("application/x-www-form-urlencoded;charset=UTF-8".equals(request.getContentType())){  
                    for (Iterator i = parameters.keySet().iterator(); i.hasNext();) {  
                        String param = (String) i.next();  
                        String[] values = (String[])parameters.get(param);  
                        if(values != null && values.length > 0){  
                            for (int j = 0; j < values.length; j++) {  
                                if(values[j] != null && !"".equals(values[j])){  
                                    try {  
                                        values[j] = URLDecoder.decode(values[j], "UTF-8");  
                                        parameters.put(param, values[j]);  
                                    } catch (UnsupportedEncodingException e1) {  
                                        e1.printStackTrace();  
                                    }   
                                }  
                            }  
                        }  
                    }  
                }         
          
                return invocation.invoke();  
            }  
        } 
    配置文件如
    <interceptors>  
                <interceptor name="urlDecodeFilterInterceptor"  
                    class="com.whaty.platform.sso.web.interceptor.UrlDecodeFilterInterceptor">  
                </interceptor>  
                  
                <interceptor-stack name="urlDecodeStack">  
                    <interceptor-ref name="urlDecodeFilterInterceptor"></interceptor-ref>  
                    <interceptor-ref name="defaultStack"></interceptor-ref>  
                </interceptor-stack>  
                  
            </interceptors>
    
    当然,处理编码集可以通过springmvc自带的过滤器进行拦截,只需要在web.xml中配置即
    
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>

    自定义一个过滤器:
    定义一个类去实现Filter.
    代码实现
    public class JspExportFilter implements Filter {
    	@Override
    	public void destroy() {
    		
    	}
    	
    	@Override
    	public void doFilter(ServletRequest request, ServletResponse response,
    		FilterChain chain) throws IOException, ServletException {
    		//判断导出格式
    		String type= request.getParameter("t");
    		
    		//文件名称(解码)
    		String exportName = URLDecoder.decode(request.getParameter("n"),"UTF-8");
    		
    		//编码
    		exportName = URLEncoder.encode(exportName, "UTF-8");
    		
    		if(exportName == null || exportName.isEmpty()){
    			exportName = "export";
    		}
    	
    		if(type==null){
    			//null
    			chain.doFilter(request, response);
    			return;
    		}
    		//使用我们自定义的响应包装器来包装原始的ServletResponse
    		ResponseWrapper wrapper = new ResponseWrapper((HttpServletResponse)response);
    		//这句话非常重要,注意看到第二个参数是我们的包装器而不是response
    		chain.doFilter(request, wrapper);
    		String result = wrapper.getResult();
    		HttpServletResponse httpResp = (HttpServletResponse) response;
    		httpResp.reset();
    		response.setCharacterEncoding("UTF-8");
    		httpResp.setContentType("application/download");
    	
    		ServletOutputStream sos = response.getOutputStream();
    		try{
    			if("xls".equals(type)){
    				//xls
    				String place="<html xmlns:v=\"urn:schemas-microsoft-com:vml\" "
    						+ "xmlns:o=\"urn:schemas-microsoft-com:office:office\" "
    						+ "xmlns:w=\"urn:schemas-microsoft-com:office:excel\" "
    						+ "xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" "
    						+ "xmlns=\"http://www.w3.org/TR/REC-html40\">";
    				result = result.replace("<html>", place);
    				httpResp.addHeader("Content-Disposition", "attachment;filename="+exportName+".xls");
    				sos.write(result.getBytes("UTF-8"));
    			}else if("doc".equals(type)){
    				//doc
    				String place="<html xmlns:v=\"urn:schemas-microsoft-com:vml\" "
    						+ "xmlns:o=\"urn:schemas-microsoft-com:office:office\" "
    						+ "xmlns:w=\"urn:schemas-microsoft-com:office:word\" "
    						+ "xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" "
    						+ "xmlns=\"http://www.w3.org/TR/REC-html40\">";
    				result = result.replace("<html>", place);
    				httpResp.addHeader("Content-Disposition", "attachment;filename="+exportName+".doc");
    				sos.write(result.getBytes("UTF-8"));
    			}else if("pdf".equals(type)){
    				//pdf
    				httpResp.addHeader("Content-Disposition", "attachment;filename="+exportName+".pdf");
    				try {
    					this.htmlCodeComeString(result, response.getOutputStream());
    				} catch (Exception e) {
    					BeanLog.getLogger().fatal("pdf export", e);
    					throw new IOException("pdf export", e);
    				}
    			}
    		}finally{
    			sos.close();
    			response.flushBuffer();
    		}
    	}
    	
    	@Override
    	public void init(FilterConfig filterConfig) throws ServletException {
    		
    	}
    	
    	private void htmlCodeComeString(String htmlCode, OutputStream outstream) throws Exception {
    		Document doc = new Document(PageSize.A4.rotate());
    		try {
    			PdfWriter writer =PdfWriter.getInstance(doc, outstream);
    			ByteArrayInputStream bis = new ByteArrayInputStream(htmlCode.getBytes("UTF-8"));
    			// 解决中文问题:需要在导出jsp的样式中设置font-family: SimSun。例如:
    			/*
    			body{
    				font-size:12.0px; font-family: SimSun;
    			}
    			*/
    			//jsp必须是xhtml,而且头必须引入
    			//<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    			doc.open();
    			XMLWorkerHelper.getInstance().parseXHtml(writer,
    					doc, bis, Charset.forName("UTF-8"));
    			doc.close();
    			bis.close();
    		}catch(Exception e) {
    			BeanLog.getLogger().fatal("pdf export", e);
    			throw e;
    		}
    	}



    
    
            在web.xml中配置

<filter>
    <filter-name>jspExport</filter-name>
    <filter-class>com.jbns.easymaster.web.sysmgr.filter.JspExportFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>jspExport</filter-name>
    <url-pattern>/export/*</url-pattern>
  </filter-mapping>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值