求解:servlet中的request的编码方式无法设置为UTF-8

源码如下

servlet源码:

@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Map<String, String[]> parameterMap = request.getParameterMap();
        System.out.println(parameterMap);
        Set<String> keySet = parameterMap.keySet();
        for (String key : keySet) {
            String[] values = parameterMap.get(key);
            System.out.println(key + " = " + Arrays.asList(values));
        }
        System.out.println("----------------------------");
        String team = request.getParameter("team");//只能获取其中的一个值
        System.out.println("team = " + team);

        String[] seasons = request.getParameterValues("season");//获取单选框的请求参数
        System.out.println("Arrays.asList(seasons)" + Arrays.asList(seasons));

        // getParameterValues()方法:取多选框的请求参数
        String[] teams = request.getParameterValues("team");
        System.out.println("Arrays.asList(teams) = " + Arrays.asList(teams));
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter writer = response.getWriter();
        writer.write("你好,我是你爸爸");

    }
}

filter源码

public class ServletFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器正在执行中,请稍等...");
//        servletRequest.setCharacterEncoding("UTF-8");
        String message = servletRequest.getParameter("message");
        if (message.equals("index")){
            filterChain.doFilter(servletRequest,servletResponse);
        } else {
            servletRequest.getRequestDispatcher("EmployeeServlet").forward(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}

在使用过滤器是遇到一个想不通的问题:当我使用过滤器ServletFilter拦截IndexServlet时,在IndexServlet设置的request的编码方式为request.setCharacterEncoding("UTF-8");,然后正常执行项目,但是发现在控制台输出有乱码,可见并没有成功编码;然后我把编码提前在过滤器ServletFilter中,发现成功设置编码了,哪位大佬可告诉我是什么原因

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值