码迷,mamicode.com
首页 > 编程语言 > 详细

Spring中过滤器+监听器的使用

时间:2017-06-08 19:39:51      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:定义   web资源   efi   format   eth   pac   pcl   程序   link   

过滤器:

  过滤器放在web资源之前,可以在请求抵达它所应用的web资源(可以是一个Servlet、一个Jsp页面,甚至是一个HTML页面)之前截获进入的请求,并且在它返回到客户之前截获输出请求。Filter:用来拦截请求,处于客户端与被请求资源之间,目的是重用代码。Filter链,在web.xml中哪个先配置,哪个就先调用。在filter中也可以配置一些初始化参数。

  

Filter 有如下几个种类:

  用户授权的Filter: Filter 负责检查用户请求,根据请求过滤用户非法请求。 

  日志Filter: 详细记录某些特殊的用户请求。 

  负责解码的Filter: 包括对非标准编码的请求解码。

创建一个Filter 只需两个步骤: 
  (1)创建Filter 处理类: 

  (2)在web.xml 文件中配置Filter 。

Spring中固有的过滤器:

<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>
  <init-param>
  <param-name>forceEncoding</param-name>
  <param-value>true</param-value>
  </init-param>
  </filter>
  <filter-mapping><!--过滤器映射的地址-->
  <filter-name>encodingFilter</filter-name>
  <url-pattern>*</url-pattern>
  </filter-mapping>

  自定义过滤器:

   1、 指定ip访问的过滤器:

 <filter>
  <filter-name>ipFilter</filter-name>
  <filter-class>com.common.filter.RequestIPFilter</filter-class>
  </filter>
  <filter-mapping>
  <filter-name>ipFilter</filter-name>
  <url-pattern>*</url-pattern>
  </filter-mapping>

package http;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestIPFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		String allowIps="";
		try {
			allowIps = PropertiesUtils.getInstance().getProperties("ip.filter");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		if(allowIps.isEmpty()){
			chain.doFilter(req, res);
		}else{
			String[] ips = allowIps.split(";");
			Map<String,String> map = new HashMap<String,String>();
			for(int i=0;i<ips.length;i++){
				map.put(ips[i], ips[i]);
			}
			String ip = HttpHelper.getClientIp(request);
			if(map.containsKey(ip)){
				chain.doFilter(req, res);
			}else{
				response.sendError(response.SC_UNAUTHORIZED, request.getRequestURI());
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}

  2、加载请求时间过滤器

技术分享
1   <filter>
2   <filter-name>timeFilter</filter-name>
3   <filter-class>com.common.filter.RequestTimeFilter</filter-class>
4   </filter>
5   <filter-mapping>
6   <filter-name>timeFilter</filter-name>
7   <url-pattern>*</url-pattern>
8   </filter-mapping>
View Code

 

 

 1 import java.io.IOException;
 2 import java.text.DateFormat;
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 import java.util.LinkedHashMap;
 6 import java.util.Map;
 7 
 8 import javax.servlet.Filter;
 9 import javax.servlet.FilterChain;
10 import javax.servlet.FilterConfig;
11 import javax.servlet.ServletException;
12 import javax.servlet.ServletRequest;
13 import javax.servlet.ServletResponse;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19 import org.springframework.util.StringUtils;
20 public class RequestTimeFilter implements Filter{
21     private static Logger logger = LoggerFactory.getLogger(RequestTimeFilter.class);
22     @Override
23     public void destroy() {
24         // TODO Auto-generated method stub
25         
26     }
27 
28     @Override
29     public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
30             throws IOException, ServletException {
31         // TODO Auto-generated method stub
32         HttpServletRequest request = (HttpServletRequest) req;
33         HttpServletResponse response = (HttpServletResponse) res;
34         DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
35         logger.info("{}----{}接收请求时间:{}-------", request.getRequestURL(),df.format(new Date()));
36         long begin = System.currentTimeMillis();
37         filterChain.doFilter(req, res);
38         logger.info("{}-----{}处理请求的时间ms:------", request.getRequestURL(), System.currentTimeMillis()-begin);
39     }
40 
41     @Override
42     public void init(FilterConfig arg0) throws ServletException {
43         // TODO Auto-generated method stub
44         
45     }
46 
47 }

3、加载数据库连接过滤器

技术分享
1   <!-- 加载连接过滤器 -->
2   <filter>
3   <filter-name>connectionFilter</filter-name>
4   <filter-class>com.common.filter.RequestConnectionFilter</filter-class>
5   </filter>
6   <filter-mapping>
7   <filter-name>connectionFilter</filter-name>
8   <url-pattern>*</url-pattern>
9   </filter-mapping>
View Code
技术分享
 1 import java.io.IOException;
 2 import java.sql.SQLException;
 3 
 4 import javax.servlet.Filter;
 5 import javax.servlet.FilterChain;
 6 import javax.servlet.FilterConfig;
 7 import javax.servlet.ServletException;
 8 import javax.servlet.ServletRequest;
 9 import javax.servlet.ServletResponse;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 public class RequestConnectionFilter implements Filter{
14 
15     @Override
16     public void destroy() {
17         // TODO Auto-generated method stub
18         
19     }
20 
21     @Override
22     public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
23             throws IOException, ServletException {
24         // TODO Auto-generated method stub
25         try{
26             filterChain.doFilter(request, response);
27         }finally{
28                 try {
29                     CommonDao.closeConnection();
30                 } catch (SQLException e) {
31                     // TODO Auto-generated catch block
32                     e.printStackTrace();
33                 }
34         }
35     }
36 
37     @Override
38     public void init(FilterConfig arg0) throws ServletException {
39         // TODO Auto-generated method stub
40         
41     }
View Code

监听器:

  现在来说说Servlet的监听器Listener,它是实现了javax.servlet.ServletContextListener 接口的服务器端程序,它也是随web应用的启动而启动,只初始化一次,随web应用的停止而销毁。主要作用是:做一些初始化的内容添加工作、设置一些基本的内容、比如一些参数或者是一些固定的对象等等。

  1、ContextLoaderListener监听器

技术分享
1 <!-- ContextLoaderListener监听器启动Web容器 -->
2   <listener>
3   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
4   </listener>
View Code

  2、读取配置文件监听器

技术分享
1   <!-- 读取配置文件的监听器 -->
2   <listener>
3   <listener-class>com.kingdee.opensys.common.util.ReadPropertiesListener</listener-class>
4   </listener>
View Code
技术分享
 1 import javax.servlet.ServletContextEvent;
 2 import javax.servlet.ServletContextListener;
 3 
 4 public class ReadPropertiesListener implements ServletContextListener{
 5 
 6     public void contextDestroyed(ServletContextEvent sce) {
 7         // TODO Auto-generated method stub
 8         
 9     }
10 
11     public void contextInitialized(ServletContextEvent sce) {
12         // TODO Auto-generated method stub
13         String path = sce.getServletContext().getRealPath("/WEB-INF/config/common.properties");
14         PropertiesUtils.init(path);
15     }
16 
17 }
18 
19 
20 
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.util.Properties;
25 
26 public class PropertiesUtils {
27 
28     private static PropertiesUtils parse = new PropertiesUtils();
29     private static Properties properties;
30     private static String path;
31     
32     public static void init(String path){
33         parse.path = path;
34         System.out.println("properties================="+path);
35     }
36 
37     public static String getProperties(String host) {
38         return properties.getProperty(host);
39     }
40 
41     public static void setProperties(String key,String value) {
42         properties.setProperty(key, value);
43     }
44     
45     public PropertiesUtils(){
46         
47     }
48     
49     public static PropertiesUtils getInstance() throws Exception{
50         if(properties==null){
51             properties = new Properties();
52             FileInputStream in = new FileInputStream(new File(path));
53             properties.load(in);
54         }
55         return parse;
56     }
57 }
58 
59 
60 
61 public class URLHelper {
62 
63     public static String getBaseUrl(String hostKey) throws Exception{
64         return PropertiesUtils.getInstance().getProperties(hostKey);
65     }
66 }
View Code

  3、Spring日志监听器

技术分享
1    <!-- log4j配置文件位置 -->
2     <context-param>
3     <param-name>log4jConfigLocation</param-name>
4     <param-value>/WEB-INF/classes/config/log4.properties</param-value>
5     </context-param>
6     <!-- 利用spring来使用log4j -->
7     <listener>
8     <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
9     </listener>
View Code

 

Spring中过滤器+监听器的使用

标签:定义   web资源   efi   format   eth   pac   pcl   程序   link   

原文地址:http://www.cnblogs.com/youzhongmin/p/6940418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!