Garbage code is a relatively common problem in j2ee. If you encounter one or two problems, you can use new String(request.getParameter(xxx).getBytes("ISO-8859-1"),"UTF-8") to solve it. In case of many cases, it is best to use a filter.
Only two things need to be paid attention to for filters - class and web.xml
1. The posting on web.xml is as follows:
<fileter> <!-- Class name --> <filter-name>SetCharsetEncodingFilter</filter-name> <!-- Class Path --> <filter-class>SetCharacter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <filter-mapping> <filter-name>SetCharsetEncodingFilter</filter-name> <!-- Set all files to be intercepted when they encounter filters --> <url-pattern>/*</url-pattern> </filter-mapping> </fileter>
2. Filter category
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; public class SetCharacter implements Filter { protected String encoding = null; protected FilterConfig filterConfig = null; protected boolean ignore = true; public void init(FilterConfig arg0) throws ServletException { this.encoding = arg0.getInitParameter("encoding"); String value = arg0.getInitParameter("imnore"); if (value == null) { this.ignore = true; } else if (value.equalsIgnoreCase("true")) { this.ignore = true; } } public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { if (ignore || (arg0.getCharacterEncoding() == null)) { String encoding = selectEncoding(arg0); if (encoding != null) arg0.setCharacterEncoding(encoding); } arg2.doFilter(arg0, arg1); } private String selectEncoding(ServletRequest arg0) { return (this.encoding); } public void destroy() { this.encoding = null; this.filterConfig = null; } } In the web.xml file, the following syntax is used to define the mapping:
1. The ones starting with "/" and ending with "/*" are used for path mapping.
2. The prefix "*." begins with an extended mapping.
3. Use "/" to define the default servlet mapping.
4. The rest are used to define detailed mappings. For example: /aa/bb/cc.action
The above is the idea of solving the Java J2EE garbled code problem. I will share it with you. I hope that you can solve similar problems smoothly when encountering them.