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.HttpServletResponse
import org.omg.CORBA.Request
public class EncodeFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("字符编码过滤器")
HttpServletRequest request = (HttpServletRequest)req
HttpServletResponse response = (HttpServletResponse)res
request.setCharacterEncoding("UTF-8")
chain.doFilter(request, response)
}
@Override
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
}
}
以上就是Filter过滤器的代码, 都设置成UTF-8 支持中文, 写好了以上代码之后,要在web.xml文件中进行配置。
1、首先编写一个Java类的filter代码。 *** 作步骤:(1)在myeclipse中新建一个java类,
(2)单击“Add”按钮,在d出来的对话框中“选择接口”文本框中输入Filter,
并选择匹配好的类型javax.servlet
(3)单击“OK”按钮返回"New Java Class"对话,然后单击“Finish”按钮,就可以看到创建的过滤器框架:
过滤器类:Encoding.java,代码如下:
package com
import java.io.IOException
import javax.servlet.*
public class Encoding implements Filter {
protected String encoding=null
protected FilterConfig config
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(request.getCharacterEncoding()==null){
//得倒指定的编码
String encode=getEncoding()
if(encode!=null){
//设置request的编码
request.setCharacterEncoding(encode)
response.setCharacterEncoding(encode)
}
}
chain.doFilter(request, response)
}
public void init(FilterConfig filterConfig) throws ServletException {
this.config=filterConfig //得到web.xml中的配置编码
this.encoding=filterConfig.getInitParameter("Encoding")
}
protected String getEncoding(){
return encoding
}
}
2、在web.xml文件写入以下代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<filter> <!-- 控制编码 -->
<filter-name>EncodingFilter</filter-name>
<filter-class>com.Encoding</filter-class>
<init-param> <!-- 初始化参数 -->
<param-name>Encoding</param-name>
<param-value>GB2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Spring有这种Filter,可以直接使用:
org.springframework.web.filter.CharacterEncodingFilter
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)