标签:oid tchar rac web web.xml 中文 局限性 orm nbsp
一、使用servlet处理的局限性
可以通过:
request.setCharacterEncoding("UTF-8");
正确获取UTF-8编码的中文,但是如果有很多servlet都需要获取中文,那么就必须在每个Servlet中增加这段代码。
有一个简便的办法,那就是通过Filter过滤器进行中文处理 ,那么所有的Servlet都不需要单独处理了。
二、使用Filter处理
创建一个EncodingFilter,设置如下代码:
1 package filter; 2 3 import java.io.IOException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 import javax.servlet.Filter; 8 import javax.servlet.FilterChain; 9 import javax.servlet.FilterConfig; 10 import javax.servlet.ServletException; 11 import javax.servlet.ServletRequest; 12 import javax.servlet.ServletResponse; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 public class EncodingFilter implements Filter { 17 18 @Override 19 public void destroy() { 20 21 } 22 23 @Override 24 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 25 throws IOException, ServletException { 26 HttpServletRequest request = (HttpServletRequest) req; 27 HttpServletResponse response = (HttpServletResponse) res; 28 29 request.setCharacterEncoding("UTF-8"); 30 31 chain.doFilter(request, response); 32 } 33 34 @Override 35 public void init(FilterConfig arg0) throws ServletException { 36 37 } 38 39 }
doFilter方法的第一个参数req,是ServletRequest 类型的,不支持setCharacterEncoding,所以要先强制转换为HttpServletRequest
三、配置web.xml
1 <filter> 2 <filter-name>EncodingFilter</filter-name> 3 <filter-class>filter.EncodingFilter</filter-class> 4 </filter> 5 6 <filter-mapping> 7 <filter-name>EncodingFilter</filter-name> 8 <url-pattern>/*</url-pattern> 9 </filter-mapping>
在SpringMVC中,web.xml配置与上面类似:
1 <filter> 2 <filter-name>CharacterEncodingFilter</filter-name> 3 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 4 <init-param> 5 <param-name>encoding</param-name> 6 <param-value>utf-8</param-value> 7 </init-param> 8 </filter> 9 <filter-mapping> 10 <filter-name>CharacterEncodingFilter</filter-name> 11 <url-pattern>/*</url-pattern> 12 </filter-mapping>
标签:oid tchar rac web web.xml 中文 局限性 orm nbsp
原文地址:https://www.cnblogs.com/Mmumu/p/8983800.html