Filterpost請求中文字元編碼的過濾器 --學習筆記

Jack2k發表於2021-09-09

java程式碼:

import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet1 extends HttpServlet {    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        //request.setCharacterEncoding("utf-8");        String username = request.getParameter("username");        String passwrod = request.getParameter("passwrod");        //顯示        response.getWriter().write("使用者名稱 :"+username);        response.getWriter().write("密碼:"+passwrod);    }}

Filter程式碼

import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class FilterDemo3 implements Filter {    private FilterConfig filterConfig;    public FilterDemo3()    {    }    public void init(FilterConfig filterConfig) throws ServletException {        this.filterConfig = filterConfig;    }    //Web容器呼叫    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {        String encoding = filterConfig.getInitParameter("encoding");        //POST請求編碼設定        request.setCharacterEncoding(encoding);        //響應編碼設定        response.setContentType("text/html;charset="+encoding);        chain.doFilter(request,response);    }    public void destroy() {    }}

login.jsp

HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">      登陸頁面                            <!--        --&gt        
                                                                                                                                                         
使用者登陸
使用者名稱             
使用者密碼             
                             
    
  

web.xml

        FilterDemo3        cn.web.servlet.filter.FilterDemo3                   encoding           UTF-8                        FilterDemo3        /*    

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/36/viewspace-2814357/,如需轉載,請註明出處,否則將追究法律責任。

相關文章