java servlet之过滤器1(解决jsp之间POST方式数据传递乱码)

时间:2025-01-19 13:36:20
  1. 首先,看看没有解决乱码的效果,新建两个jsp页面(a.jsp跳转到b.jsp)。
         <form action="b.jsp" method="post">
    <input type="text" name="testarea">
    <input type="submit" value="提交">
    </form>
       <%
    String data = request.getParameter("testarea");
    %>
    接收到的结果是:<%=data %>

    运行效果图如下(b.jsp)中出现乱码:

    java servlet之过滤器1(解决jsp之间POST方式数据传递乱码)java servlet之过滤器1(解决jsp之间POST方式数据传递乱码)

  2.现在建一个过滤器来解决乱码问题。

    右键src新建servlet,取个名字(如,EncodingServlet),实现servlet中的Filter接口,确定后,添加未实现的方法。代码如下:

 import java.io.IOException;
import java.io.PrintWriter; 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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class EncodingServlet extends HttpServlet implements Filter { public void destroy() {
super.destroy();
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if(httpRequest.getMethod().toUpperCase().equals("POST")){
httpRequest.setCharacterEncoding("utf-8");
chain.doFilter(httpRequest, httpResponse);
}else
chain.doFilter(httpRequest, httpResponse);
} @Override
public void init(FilterConfig filterConfig) throws ServletException { } }

    代码解释:

    23-24行:将ServletRequest和ServletResponse对象强转为HttpServletRequest和HttpServletResponse对象;

    25行:将得到的传输方法得到并转为大写再与POST比较

    26行:设置字符编码为UTF-8,因为setCharacterEncoding方法在HttpServletRequest中才有,所以才有23-24行的强转操作;

    27行:chain.doFilter(httpRequest, httpResponse);相当于放行,通过过滤器。

    需要配置web.xml文件,如下:

   <filter>
<filter-name>EncodingServlet</filter-name>
<filter-class>cn.cqvie.filter.EncodingServlet</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingServlet</filter-name>
<url-pattern>/*</url-pattern><!--作用范围为本项目中的所有页面-->
</filter-mapping>

现在重启服务器(最好重新部署一下项目),再次访问a.jsp页面和b.jap页面,就没有乱码了。

java servlet之过滤器1(解决jsp之间POST方式数据传递乱码)java servlet之过滤器1(解决jsp之间POST方式数据传递乱码)

初学者,见笑!

  13:35:36 2016-11-20