添加过滤器
创建一个filter包在下面创建SetCharacterEncodingFilter的类
package 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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class SetCharacterEncodingFilter implements Filter {
class Request extends HttpServletRequestWrapper
{
public Request(HttpServletRequest request) {
super(request);
}
public String toUTF8(String input) {
try {
byte[] bytes = input.getBytes("ISO8859-1");
return new String(bytes, "utf-8");
} catch (Exception ex) {
}
return null;
}
private HttpServletRequest getHttpServletRequest()
{
return (HttpServletRequest) super.getRequest();
}
public String getParameter(String name)
{
return
toUTF8(getHttpServletRequest().getParameter(name));
}
public String[] getParameterValues(String name)
{
String values[] =getHttpServletRequest().getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = toUTF8(values[i]);
}
}
return values;
}
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse
response,FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpreq = (HttpServletRequest) request;
if (httpreq.getMethod().equals("POST")) {
request.setCharacterEncoding("utf-8");
} else {
request = new Request(httpreq);
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws
ServletException {
}
}
在web.xml里添加如下代码
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>filter.SetCharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
到这里OK了
但这种方法会有一种问题。进行模糊查询时,req.getParameter读取jsp页面的中文会变成问号导致无法查询中文的只能查英文的
所以还有一种方法,不用过滤器直接在req.getParameter上转换
String dishname=new String(req.getParameter("dishname").getBytes("ISO-8859-1"),"UTF-8");
这种方法就是麻烦点