our default encoding of actions all is UTF-8.
[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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>securityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</filter-name>
</filter>
-----
In order to allow some actions using other encoding(ex:Shift-JIS) different with default encoding(UTF-8), we should use EncodingFilter class as a new filter and
define it before FilterDispatcher.
[original URL :http://hamasyou.com/archives/Engineer-Soul/struts2_ue_xwork.php]
Added portion
<filter>
<filter-name>encoding</filter-name>
<filter-class> util.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<!--new encoding which System needs to suppport-->
<param-value>Shift_JIS</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<!--specialcoding.action is the action which System needs to support with Shift_JIS-->
<url-pattern>/specialencoding.action</url-pattern>
</filter-mapping>
Content of EncodingFilter.java:
package util;
import java.io.IOException;
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;
public class EncodingFilter implements Filter {
private String encoding;
public void destroy() {
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest r = (HttpServletRequest) request;
r.setCharacterEncoding(encoding);
r.getParameter("foobar"); //commit encoding
}
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
String enc = config.getInitParameter("encoding");
if (enc != null) {
encoding = enc;
}
}
}
No comments:
Post a Comment