`
_Yggd
  • 浏览: 90545 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

关于struts2字符过滤器有趣的代码,过滤器有问题的童靴可以戳进来看看

阅读更多
以下是struts2的拦截器 字符过滤(网上代码有很多,都和这个差不多(我亲测以后发现字符过滤还是不行,就自己弄了一个)):

有一个最简单的方法就是在你的struts.xml文件中添加:
<constant name="struts.i18n.encoding" value="GBK" /
>


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fyz.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.StrutsRequestWrapper;
import org.apache.struts2.interceptor.ServletRequestAware;

/**
*
* @author RDGFT
*/
public class EncodingInterceptor extends AbstractInterceptor {

    private HttpServletRequest request;

    /**
     * @return the request
     */
    public HttpServletRequest getRequest() {
return request;
    }

    /**
     * @param request the request to set
     */
    public void setRequest(HttpServletRequest request) {
this.request = request;
    }

    private class Request extends StrutsRequestWrapper {
//从web.xml文件中设置的编码

private String encoding = null;
//构造器

public Request(HttpServletRequest request) {
    super(request);
    encoding = "gbk";//设置编码
}

/**
* 转换编码,由原来的西欧字符集转换成为设定的预设字符集
*/
public String Encoding(String input) {
    if (input == null) {
return null;
    } else {
try {
    return new String(input.getBytes("iso-8859-1"), encoding);
} catch (UnsupportedEncodingException ex) {
    Logger.getLogger(EncodingInterceptor.class.getName()).log(Level.SEVERE, null, ex);
}
    }
    return null;
}

/**
* Return the HttpServletRequest holded by this object.
*/
private HttpServletRequest getHttpServletRequest() {
    return (HttpServletRequest) super.getRequest();
}

/**
* 对父类的方法进行重写
*/
@Override
public String getParameter(String name) {
    return Encoding(getHttpServletRequest().getParameter(name));
}

/**
* 对父类的方法进行重写
*/
@Override
public String[] getParameterValues(String name) {
    String values[] = getHttpServletRequest().getParameterValues(name);
    if (values != null) {
for (int i = 0; i < values.length; i++) {
    values[i] = Encoding(values[i]);
}
    }
    return values;
}
    }

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
ActionContext actionContext = ai.getInvocationContext();
this.request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
if (this.request.getMethod().compareToIgnoreCase("post") >= 0) {
    this.getRequest().setCharacterEncoding("GBK");
    System.out.println("进入拦截器post");

} else {
    this.setRequest(new Request(this.request));
    System.out.println("进入拦截器get");
}
return ai.invoke();
    }
}


关于上述代码,我根据网上的代码改了改,初级版本是继承RequestAware(是不是这个,大家明白就行了)接口,但是request是null
你现在看到的版本扩展了request不是null(转码失败),


struts.xml文件:
<interceptors>
    <interceptor name="Encoding" class="com.fyz.interceptor.EncodingInterceptor"></interceptor>
    <interceptor-stack name="Encod">
<interceptor-ref name="Encoding"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref><!-- 必须引入这个,否则request不会再往下传-->
    </interceptor-stack>
</interceptors>
<default-interceptor-ref name="Encod"></default-interceptor-ref>

大家可以试试是不是我说的那样



以下struts2过滤器本人亲测是可行的代码:


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fyz.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;



/**
*
* @author RDGFT
*/
public class EncodingFilter extends StrutsPrepareAndExecuteFilter implements Filter{
   private String encoding = "";

    //扩展原来的request,使原来的用get方法得到的参数转换成相应的编码,不影响原来的功能
    private class Request extends HttpServletRequestWrapper {
//从web.xml文件中设置的编码

private String encoding = null;
//构造器

public Request(HttpServletRequest request) {
    super(request);
    encoding = this.encoding;//设置编码
}

/**
* 转换编码,由原来的西欧字符集转换成为设定的预设字符集
*/
public String Encoding(String input) {
    if (input == null) {
return null;
    } else {
try {
    System.out.println(input);
    return new String(input.getBytes("iso-8859-1"), encoding);
} catch (UnsupportedEncodingException ex) {
    Logger.getLogger(EncodingFilter.class.getName()).log(Level.SEVERE, null, ex);
}
    }
    return null;
}

/**
* Return the HttpServletRequest holded by this object.
*/
private HttpServletRequest getHttpServletRequest() {
    return (HttpServletRequest) super.getRequest();
}

/**
* 对父类的方法进行重写
*/
@Override
public String getParameter(String name) {
    return Encoding(getHttpServletRequest().getParameter(name));
}

/**
* 对父类的方法进行重写
*/
@Override
public String[] getParameterValues(String name) {
    String values[] = getHttpServletRequest().getParameterValues(name);
    if (values != null) {
for (int i = 0; i < values.length; i++) {
    values[i] = Encoding(values[i]);
}
    }
    return values;
}
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (req.getMethod().compareToIgnoreCase("post") >= 0) {
    request.setCharacterEncoding(encoding);
} else {
    request = new Request(req);
     System.out.println("get方法中");
}


chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
encoding = filterConfig.getInitParameter("encoding");
System.out.println(encoding);
    }
}

web.xml文件的配置如下:


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
   
  
   
   
    <!-- struts2的和核心过滤器-->
    <filter>
<filter-name>Struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
<filter-name>Struts2</filter-name>
<url-pattern>/*</url-pattern>
    </filter-mapping>
   
   
     <filter>
        <filter-name>CharsetEncodingFilter</filter-name>
        <filter-class>com.fyz.filter.EncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>GBK</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharsetEncodingFilter</filter-name>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
        <dispatcher>ANSYC</dispatcher>
        <!-- 异步处理请求-->
        <!--对全站点进行编码转换 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
   
    <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <session-config>
<session-timeout>
    30
</session-timeout>
    </session-config>
    <jsp-config>
<taglib>
    <taglib-uri>http://com.fyz/tagslib</taglib-uri>
    <taglib-location>/WEB-INF/mypage.tld</taglib-location>
</taglib>
    </jsp-config>
</web-app>


[align=left]注意:

[/align]

web.xml文件过滤器的配置的顺序问题。一定是自定义的过滤器在前,然后struts2的
核心过滤器在后(要不然还是转码失败)


希望路过的各位大神不吝赐教
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics