JavaWeb修改請求參數信息

客戶端發送請求:http://localhost:8080/test/xxx.action?name="palading"&age=24

        HttpServlet類中調用:

        Map<String, String[]>map=request.getParameterMap();
        for(String key:map.keySet()){
        if(key.equals("name")){
        map.put("name",new String[]{"小明"});
        }
        }

        HttpServlet引發異常
        java.lang.IllegalStateException:No modifications are allowed to a locked ParameterMap

        默認情況下只能查看請求參數信息,不能修改參數信息。
        所以繼承要HttpServletRequestWrapper重寫getParameter方法:

public class MyHttpServletWrapp extends HttpServletRequestWrapper {
    HttpServletRequest request;

    public MyHttpServletWrapp(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    @Override
    public String getParameter(String name) {
        if ("name".equals(name))
            return "Test";
        return super.getParameter(name);
    }

}


新建過濾器類 implements Filter
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException,ServletException{
        MyHttpServletWrapp myHttpServletWrapp=new MyHttpServletWrapp((HttpServletRequest)request);

        重新包裝發送請求
        chain.doFilter(myHttpServletWrapp,response);
        }

        在HttpServlet中獲取請求參數信息 發現請求參數信息已經被改變
protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{

        String name=request.getParameter("name");
        System.out.println(name);

        }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章