JSP uses filters to solve the problem of Chinese garbled codes in request

  • 2021-10-16 02:24:13
  • OfStack

In this article, we share that JSP uses filters to solve the problem of request Chinese garbled codes. The specific contents are as follows
(1) The data of the client is generally submitted to the server by HTTP GET/POST, and request. getParameter ()
When reading parameters, it is easy to appear Chinese garbled characters.
(2) Using filter to solve the problem of request Chinese garbled code.
(3) The code is as follows:


package my; 
 
import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class ChineseFilter implements Filter { // Defines the 1 Filters   Realization Filter Interface  
 
 private FilterConfig config = null; 
 
 public void init(FilterConfig config) throws ServletException { 
 this.config = config; 
 } 
 
 public void destroy() { 
 config = null; 
 } 
 
 public void doFilter(ServletRequest request, ServletResponse response, 
      FilterChain chain) throws IOException, ServletException 
 { 
  request.setCharacterEncoding("GB2312"); 
  chain.doFilter(request, response); // Put the filtered request Object is forwarded to the following 1 Filter processing  
 } 
} 

(4) Deploy filters. Edit the WEB-INF\ web.xml file to add the following:


<filter> 
 <filter-name>cf</filter-name> 
 <filter-class>my.ChineseFilter</filter-class> 
</filter> 
<filter-mapping> 
 <filter-name>cf</filter-name> 
 <url-pattern>/*</url-pattern> 
 <dispatcher>REQUEST</dispatcher> 
 <dispatcher>FORWARD</dispatcher> 
 <dispatcher>INCLUDE</dispatcher> 
</filter-mapping> 

Here's < dispatcher > < /dispatcher > It is mainly used with RequestDispatcher.

1. When the value is REQUEST, it means that the filter can be activated only when the request comes directly from the client, but it will not be activated if the request comes from RequestDispatcher. forward; 2. A value of FORWARD indicates that this filter is activated if the request is from RequestDispatcher. forward; 3. A value of INCLUDE indicates that this filter is activated if the request is from RequestDispatcher. include; 4. When the value is ERROR, it means that this filter will be activated if the request is from RequestDispatcher and the "Error Message Page" is used; 5. The default is REQUEST.

(5) Create an jsp page validation


<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<title> Untitled document </title> 
</head> 
 
<body> 
<% 
  String s=request.getParameter("data"); 
  out.print(s); 
%> 
</body> 
</html> 

The above is about JSP to solve the problem of request Chinese garbled code, hoping to help everyone's study.


Related articles: