Struts2 Chinese messy code solution sharing
- 2020-04-01 02:52:40
- OfStack
Fit the situation -> From the JSP passed into the action of the garbled code, here to GBK as an example
1. Create a filter for conversion coding
File location, for example: the SRC. Util. SetCharacterEncodingFilter. 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.UnavailableException;
public class SetCharacterEncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {
request.setCharacterEncoding("gbk");
//Pass control to the next filter
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
2. Modify web.xml to add 2 filters before the struts FilterDispatcher mapping
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>util.SetCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3. Your JSP header should have
< % @ page language = "Java" pageEncoding = "GBK" % >
4. Modify the default encoding Settings in struts.xml
<struts>
<constant name="struts.i18n.encoding" value="gbk"></constant>
...
...
...
</struts>
Basically this can solve the problem of most incoming characters
PS: if it is a database extraction character chaos, such as mysql, confirm that your database character is GBK, and the connection string specified the character encoding
< The property name = "url" value = "JDBC: mysql: / / localhost/database? UseUnicode = true& CharacterEncoding = GBK "> < / property>