Filter解決get和post提交方法亂碼的實現
阿新 • • 發佈:2019-01-04
public class GenericalEncodingFilter extends HttpServletRequestWrapper{
//定義改變後的請求
private HttpServletRequest request;
public GenericalEncodingFilter(HttpServletRequest request) {
super(request);//呼叫父類的構造方法
this.request = request;
} //增強request的getParamter方法; @Override public String getParameter(String name){ //根據請求方法的不同去處理 //獲得請求方式 String method = request.getMethod(); String value=null; if("post".equalsIgnoreCase(method)){ try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return super.getParameter(name); }else if ("get".equalsIgnoreCase(method)) { try { value= new String(request.getParameter(name).getBytes("utf-8"),"utf-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return value; }
}
使用裝飾者模式增強request的getParamter()方法
注意:使用裝飾者模式的前提:【1、被增強的類和增強的類實現相同的介面,2、在增強的類中獲得被增強的類的引用】