在旧的请求参数的获取方式当中,需要对两种不同的请求方式做两份不同的代码逻辑,现在就是要统一操作,比如在post里面调用get的代码
如下图的操作
先获取请求方式,对于不同的方式都先把请求参数获取出来,这里request还完成了对字符串的解析,对&和=进行切割 之后将键值对放进map里面进行存储,对于一个键对应多个值的情况这里也有字符串数组的方式对应处理。
html页面配置如下的表单
在url后面有所提示
使用如下代码进行get方法的请求参数的获取并输出,这里是使用表单的方式进行提交,下面有三个常用的方法的演示。
@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//GET请求逻辑//System.out.println("get....");//1. 获取所有参数的Map集合Map map = req.getParameterMap();for (String key : map.keySet()) {// username:zhangsan lisiSystem.out.print(key+":");//获取值String[] values = map.get(key);for (String value : values) {System.out.print(value + " ");}System.out.println();}System.out.println("------------");//2. 根据key获取参数值,数组String[] hobbies = req.getParameterValues("hobby");for (String hobby : hobbies) {System.out.println(hobby);}//3. 根据key 获取单个参数值String username = req.getParameter("username");String password = req.getParameter("password");System.out.println(username);System.out.println(password);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//POST请求逻辑this.doGet(req,resp);
}
中文乱码了
这里不管是get方法获取还是post方法的获取都是通用,request已经帮忙处理好了,所以走post逻辑时也可以调用处理get的代码来处理。