Java 过滤器读取配置文件实现过滤编码

1.实现  javax.servlet 中的Filter 接口

filter.doFilter(request, response);是表示filter chain通过


package filter_test;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


public class FilterTest implements Filter {


String encoding = null;
@Override
public void destroy() {
encoding = null;


}


@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter)
throws IOException, ServletException {
System.out.println(encoding);
if(encoding!=null){
request.setCharacterEncoding(encoding);
   response.setContentType("text/html;charset="+encoding);
}else{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
}
filter.doFilter(request, response);
}


@Override
public void init(FilterConfig filterConfig) throws ServletException {
String path = filterConfig.getInitParameter("encoding");
String realpath = filterConfig.getServletContext().getRealPath(path);
Properties pp = new Properties();
try {
pp.load(new FileInputStream(realpath));
encoding = pp.getProperty("encoding");

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub


}

}

2.在 配置web.xml以便在程序启动的时候去加载类

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>filter_test</display-name>
 <filter>
 <filter-name>filterTest</filter-name>
 <filter-class>filter_test.FilterTest</filter-class>
 <init-param>
 <param-name>encoding</param-name>
 <param-value>/WEB-INF/set.properties</param-value>
</init-param>
 </filter>
 
 <filter-mapping>
 <filter-name>filterTest</filter-name>
 <url-pattern>/filter/result.jsp</url-pattern>
 </filter-mapping>
</web-app>

3. 在根目录 (webContent)下建立 /WEB-INF/set.properties 

内容: encoding=UTF-8

4.新建的

.

5. index.jsp 中

<body>
<a href="result.jsp">到结果页面</a>
</body>

就可以通过该过滤器链接到result.jsp

<body>
reesult.jsp
</body>







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值