The solution to the problem of Java J2EE

  • 2020-05-09 18:33:31
  • OfStack

Scrambled codes are a common problem in j2ee. In the case of 1 or 2 problems, you can use new String(request.getParameter (xxx).getBytes (" ISO-8859-1 ")," UTF-8 "). It is best to use a filter when there are many cases.
The filter only needs to pay attention to two things -- the class and web.xml
1. The post above web.xml is as follows:


<fileter> 
  <!--  The name of the class  --> 
  <filter-name>SetCharsetEncodingFilter</filter-name> 
  <!--  The path of the class  --> 
  <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 file encounter filters to be intercepted  --> 
    <url-pattern>/*</url-pattern> 
  </filter-mapping> 
</fileter> 

2. Filter class


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; 
    } else if (value.equalsIgnoreCase("yes")) { 
      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. Those that start with/and end with /* are used for path-mapping.
2. The prefix "*." is used for extended mapping.
3. "/" is used to define the default servlet mapping.
4. The rest is used to define detailed mappings. For example: / aa bb/cc action

This is the way to solve the problem of Java J2EE. I hope you can solve this problem successfully.


Related articles: