struts filter用法,网上的都是胡扯(包括本文,嘿嘿)

<filter> 
<filter-name>Set_Character_Encoding</filter-name>
<filter-class>com.baofeng.media.filter.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set_Character_Encoding</filter-name>
<url-pattern>/*</url-pattern>  //不是<servlet-name>
</filter-mapping>




不明白吗?往后看

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>


对应.指定当服务器收到.do结尾的请求的时候.调用org.apache.struts.action.ActionServlet类来处理.
action就是一个名字.只要保证两部分的<servlet-name>能够一致就ok.*.do可以改.就是个请求的字符.你的jsp中肯定在提交请求的时候.发送的是xxx.do这种

servlet-name是在配置文件里的名字,为了对应匹配的,不要瞎写,应该是红色字体部分。


以下是过滤器的代码,注意,[color=red]所有前台的请求必须是post的[/color],不然过滤器是不会管的。

 protected FilterConfig filterConfig;

protected String encodingName;

protected boolean enable;

public EncodingFilter() {
this.encodingName = "UTF-8";
this.enable = false;
}

public void init( FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
loadConfigParams();
}

private void loadConfigParams() {
this.encodingName = this.filterConfig.getInitParameter("encoding");
String strIgnoreFlag = this.filterConfig.getInitParameter("enable");
if (strIgnoreFlag.equalsIgnoreCase("true"))
{
this.enable = true;
}else
{
this.enable = false;
}
}

public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (this.enable)
{
request.setCharacterEncoding(this.encodingName);
response.setCharacterEncoding(this.encodingName);
}
chain.doFilter(request, response);
}

public void destroy() {
}



还有一点要注意:

通过 get/post 方式从 ie中发送汉字,发送编码方式由Content-Type决定,request.getParameter("XX")得到的字符串是用ISO-8859-1表示的,所以必须在取值前用HttpServeletRequest.setCharacterEncoding 设置想得到的编码类型,或是在<Connector>中添加URIEncoding="GBK"属性,来获取正确的编码类型。

但是,在执行setCharacterEncoding()之前,不能执行任何getParameter()。

java doc上说明:This method must be called prior to reading request parameters or reading input using getReader()。而且,该指定只对POST方法有效,对GET方法无效。分析原因,应该是在执行第一个getParameter()的时候, java将会按照编码分析所有的提交内容,而后续的getParameter()不再进行分析,所以setCharacterEncoding()无效。 而对于GET方法提交表单是,提交的内容在URL中,一开始就已经按照编码分析所有的提交内容,setCharacterEncoding()自然就无效。

摘自:[url]http://www.blogjava.net/xyang/archive/2006/09/28/72343.html[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值