Java Web form 提交信息中文乱码的解决办法

最简单的办法

Servlet 里处理响应的方法最顶上加上一行代码
req?.characterEncoding = Charsets.UTF_8.toString()

具体如下

override fun doPost(req: HttpServletRequest?, resp: HttpServletResponse?) {
        req?.characterEncoding = Charsets.UTF_8.toString()
        val userName = req?.getParameter("u").toString()
        val passwd = req?.getParameter("p").toString()
        val user = UserBeen(userName, passwd)
        val cookies = user.toCookie()
        resp?.let {
            for (cookie in cookies) {
                it.addCookie(cookie)
            }
        }
        req?.let {
            it.session.setAttribute("mySession", user)
            it.setAttribute("result", user)
            it.getRequestDispatcher("/index.jsp").forward(it, resp)
        }
    }

比较复杂的办法

使用 WebFilter

doFilter 里拦截请求后修改字符编码再使用 chain 发给后方 Servlet

urlPatternsWebFilter 生效范围

package com.mrx.myservlet

import javax.servlet.*
import javax.servlet.annotation.WebFilter

@WebFilter(filterName = "/encodingChanger", urlPatterns = ["/*"])
class WebFilter : Filter {
    private var filterConfig: FilterConfig? = null

    override fun init(filterConfig: FilterConfig?) {
        this.filterConfig = filterConfig
        println("init Filter")
    }

    override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) {
        request?.characterEncoding = "UTF-8"
        response?.characterEncoding = "UTF-8"
        println("do Filter")
        chain?.doFilter(request, response)
    }

    override fun destroy() {
        filterConfig = null
    }
}
posted @ 2021-09-09 10:14  博麗靈夢  阅读(55)  评论(0编辑  收藏  举报