我有一个用于设置字符编码过滤器的过滤器。
web.xml:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>ua.com.winforce.online.site.http.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
过滤器本身:
public class EncodingFilter implements Filter {
private static final String ENCODING = "UTF-8";
FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
request.setCharacterEncoding(ENCODING);
filterChain.doFilter(request, response);
}
public void destroy() {
}
}
一段标记用户提交表单:
<h:form>
<h:commandLink styleClass="ruski-button green-g full-width" action="#{supportController.save}" >
</h:commandLink>
</h:form>
事情是当 post 请求到来时,过滤器的方法 doFilter
在 supportController.save
方法之前调用。但我需要在 supportController.save
调用之前设置字符编码。我怎样才能做到这一点?
最佳答案
更改过滤器映射
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
至
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
SRV.11.2 Specification of Mappings
In the web application deployment descriptor, the following syntax is used to define mappings:
- A string beginning with a ‘/’ character and ending with a ‘/*’ postfix is used for path mapping.
- A string beginning with a ‘*.’ prefix is used as an extension mapping.
- A string containing only the ’/’ character indicates the "default" servlet of the application. In this case the servlet path is the
request URI minus the context path and the path info is null.- All other strings are used for exact matches only.
关于java - 为什么托管 bean 方法在发布请求中的过滤器调用之前调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26994464/