Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

谷哥的小弟学后台(26)——Filter(3)

$
0
0

探索Android软键盘的疑难杂症
深入探讨Android异步精髓Handler
详解Android主流框架不可或缺的基石
站在源码的肩膀上全解Scroller工作机制


Android多分辨率适配框架(1)— 核心基础
Android多分辨率适配框架(2)— 原理剖析
Android多分辨率适配框架(3)— 使用指南


自定义View系列教程00–推翻自己和过往,重学自定义View
自定义View系列教程01–常用工具介绍
自定义View系列教程02–onMeasure源码详尽分析
自定义View系列教程03–onLayout源码详尽分析
自定义View系列教程04–Draw源码分析及其实践
自定义View系列教程05–示例分析
自定义View系列教程06–详解View的Touch事件处理
自定义View系列教程07–详解ViewGroup分发Touch事件
自定义View系列教程08–滑动冲突的产生及其处理


版权声明


在这篇博客中我们利用Filter一并解决POST和GET请求的中文乱码。

测试表单

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/loginServlet" method="post">
        <br/>
        用  户:<input type="text" name="username"/><br/><br/>
        密  码:<input type="password" name="password"/><br/><br/>
        <input type="submit" value=" 登  录 " /><br/>
    </form>
</body>
</html>

该页面非常简单,在点击”登录”之后跳转到loginServlet


测试Servlet

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
package cn.com;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGetAndPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGetAndPost(req, resp);
    }

    private void doGetAndPost(HttpServletRequest req, HttpServletResponse resp){
        String username=req.getParameter("username");
        System.out.println("---> username="+username);
    }
}

在该页面中利用getParameter( )测试是否乱码


利用Filter过滤乱码

嗯哼,终于轮到今天的主角上场了

/**
 * 本文作者:谷哥的小弟
 * 博客地址:http://blog.csdn.net/lfdfhl
 */
package cn.com;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
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;
import javax.servlet.http.HttpServletResponse;

public class TestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) res;
        request=new MyHttpServletRequest(request);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}

class MyHttpServletRequest extends HttpServletRequestWrapper{
    HttpServletRequest request;
    boolean isFirst=true;

    public MyHttpServletRequest(HttpServletRequest request) {
        super(request);
        this.request=request;
    }

    @Override
    public String getParameter(String name) {
        Map<String, String[]> parameterMap=getParameterMap();
        String[] values=parameterMap.get(name);
        String value=values[0];
        return value;
    }


    @Override
    public String[] getParameterValues(String name) {
        Map<String, String[]> parameterMap=getParameterMap();
        String[] values=parameterMap.get(name);
        return values;
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> parameterMap = request.getParameterMap();
        if(isFirst){
            Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
            for(Entry<String, String[]> entry:entrySet){
                String[] values = entry.getValue();
                for(int i=0;i<values.length;i++){
                    String value=values[i];
                    try {
                        value=new String(value.getBytes("iso8859-1"),"UTF-8");
                        values[i]=value;
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
            isFirst=false;
        }
        return parameterMap;
    }
}

在该类中通过继承HttpServletRequestWrapper实现自己的HttpServletRequest,即文中的MyHttpServletRequest。

  • 覆写getParameter( )使其最终调用getParameterMap( )
  • 覆写getParameterValues( )使其最终调用getParameterMap( )
  • 在getParameterMap( )中将每个请求参数用UTF-8重新编码

配置文件

<?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">

    <filter>
        <filter-name>TestFilter</filter-name>
        <filter-class>cn.com.TestFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>TestFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>loginServlet</servlet-name>
        <servlet-class>cn.com.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>loginServlet</servlet-name>
        <url-pattern>/loginServlet</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>

嗯哼,至此利用Filter同时解决了Post和Get请求时带来的中文乱码问题。

作者:lfdfhl 发表于2017/2/24 21:39:52 原文链接
阅读:338 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>