过滤器解决中文乱码

@WebServlet(urlPatterns = "/form")
public class FormServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        response.getWriter().write("哈哈");
        System.out.println(username);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
@WebFilter(urlPatterns = "/*")
public class ChinaFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //在过滤器中,设置request对象的编码表
        servletRequest.setCharacterEncoding("utf-8");
        //设置response缓冲区的编码表,通知浏览器的解码
        servletResponse.setContentType("text/html;charset=utf-8");
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
    @Override
    public void destroy() {}
}
<body>
    <form action="${pageContext.request.contextPath}/form" method="post">
        <input type="text" name="username">
        <input type="submit">
    </form>
</body>

 

posted @ 2019-08-10 20:04  逍茗  阅读(242)  评论(0编辑  收藏  举报