标签:自定义 ssm nic conf character pre 包名 gen name
在ssm项目中经常会使用到请求、响应和页面展示等操作,都会涉及到编码的问题,一些时候会出现乱码的情况。
这里有几种设置编码的方法:
org.springframework.web.filter.CharacterEncodingFilter
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--要使用的字符集的编码格式,一般用UTF-8--> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param>
<!--是否强制设置request时的编码格式--> <init-param> <param-name>forceRequestEncoding</param-name> <param-value>false</param-value> </init-param>
<!--是否强制设置response时的编码格式--> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param>
</filter> <filter-mapping>
<filter-name>characterEncodingFilter</filter-name> <!--不能设置为“/”--> <url-pattern>/*</url-pattern> </filter-mapping>
实现Filter设置请求和响应的编码格式,并且在web.xml中进行配置
(1)配置编码类
public class SetCharacterEncodingFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //post请求 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); chain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
(2)在web.xml中配置
<filter> <filter-name>SetCharacterEncodingFilter</filter-name> <filter-class>com.util.SetCharacterEncodingFilter</filter-class>//类的全包名 <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>SetCharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
在操作数据库的时候,需要向数据库中写入值,这里也可以设置一下编码格式
jdbc:mysql:///phone?useUnicode=true&characterEncoding=utf8
标签:自定义 ssm nic conf character pre 包名 gen name
原文地址:https://www.cnblogs.com/huangcan1688/p/12183145.html