首先楼主的代码没问题。但是这样写很繁琐。如果表单中有很多文本框需要提交,那每次都要转字符格式。建议你写一个过滤器- package com.tan.oa.web.filter;
- 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 CharacterEncodingFilter implements Filter {
- private String encoding = "utf-8";
- public void destroy() {
- // TODO Auto-generated method stub
- }
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
- ServletException {
- // request中设置encoding
- if (request.getCharacterEncoding() == null) {
- request.setCharacterEncoding(encoding);
- }
- // response中设置encoding
- response.setContentType("text/html;charset=" + this.encoding);
- response.setCharacterEncoding(encoding);
- chain.doFilter(request, response);
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- // 读取filter配置参数信息
- String en = filterConfig.getInitParameter("encoding");
- if (en != null && !"".equals(en)) {
- this.encoding = en;
- }
- }
- }
复制代码 在web配置文件中配置- <!-- 解决乱码 -->
- <filter>
- <filter-name>CharsetEncodingFilter</filter-name>
- <filter-class>com.tan.oa.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>CharsetEncodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
复制代码 任何项目加上以上代码。一切乱码搞定 |