java servlet之过滤器1(解决jsp之间POST方式数据传递乱码)
- 首先,看看没有解决乱码的效果,新建两个jsp页面(a.jsp跳转到b.jsp)。
1 <form action="b.jsp" method="post"> 2 <input type="text" name="testarea"> 3 <input type="submit" value="提交"> 4 </form>
1 <% 2 String data = request.getParameter("testarea"); 3 %> 4 接收到的结果是:<%=data %>
运行效果图如下(b.jsp)中出现乱码:
2.现在建一个过滤器来解决乱码问题。
右键src新建servlet,取个名字(如,EncodingServlet),实现servlet中的Filter接口,确定后,添加未实现的方法。代码如下:
1 import java.io.IOException; 2 import java.io.PrintWriter; 3 4 import javax.servlet.Filter; 5 import javax.servlet.FilterChain; 6 import javax.servlet.FilterConfig; 7 import javax.servlet.ServletException; 8 import javax.servlet.ServletRequest; 9 import javax.servlet.ServletResponse; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 public class EncodingServlet extends HttpServlet implements Filter { 15 16 public void destroy() { 17 super.destroy(); 18 } 19 @Override 20 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 21 throws IOException, ServletException { 22 23 HttpServletRequest httpRequest = (HttpServletRequest) request; 24 HttpServletResponse httpResponse = (HttpServletResponse) response; 25 if(httpRequest.getMethod().toUpperCase().equals("POST")){ 26 httpRequest.setCharacterEncoding("utf-8"); 27 chain.doFilter(httpRequest, httpResponse); 28 }else 29 chain.doFilter(httpRequest, httpResponse); 30 } 31 32 @Override 33 public void init(FilterConfig filterConfig) throws ServletException { 34 35 } 36 37 }
代码解释:
23-24行:将ServletRequest和ServletResponse对象强转为HttpServletRequest和HttpServletResponse对象;
25行:将得到的传输方法得到并转为大写再与POST比较
26行:设置字符编码为UTF-8,因为setCharacterEncoding方法在HttpServletRequest中才有,所以才有23-24行的强转操作;
27行:chain.doFilter(httpRequest, httpResponse);相当于放行,通过过滤器。
需要配置web.xml文件,如下:
1 <filter> 2 <filter-name>EncodingServlet</filter-name> 3 <filter-class>cn.cqvie.filter.EncodingServlet</filter-class> 4 </filter> 5 <filter-mapping> 6 <filter-name>EncodingServlet</filter-name> 7 <url-pattern>/*</url-pattern><!--作用范围为本项目中的所有页面--> 8 </filter-mapping>
现在重启服务器(最好重新部署一下项目),再次访问a.jsp页面和b.jap页面,就没有乱码了。
初学者,见笑!
13:35:36 2016-11-20