HttpServletRequest类的常用方法,获取参数,解决POST中文乱码

HttpServletRequest类的常用方法

  • getRequestURI() 获取请求的资源路径
  • getRequestURL() 获取请求的统一资源定位符(资源路径)
  • getRemoteHost() 获取客户端的IP地址
  • getHeader() 获取请求头
  • getParameter() 获取请求参数
  • getParameterValues() 获取请求的参数(多个值时候使用)
  • getMethod() 获取请求的方式GET或POST
  • setAttribute(key,value); 设置域数据
  • getAttribute(key); 获取域数据
  • getRequestDispatcher() 请求转发函数
获取参数(重点使用)

首先需要编辑HTML表单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8888/7_servlet_war_exploded/ppp" method="post">
    用户名:<input type="text" name="username"> <br/>
    密码:<input type="password" name="password"> <br/>
    兴趣爱好:<input type="checkbox" name="hobby" value="java">JAVA
    兴趣爱好:<input type="checkbox" name="hobby" value="js">JavaScript
    兴趣爱好:<input type="checkbox" name="hobby" value="CPP">C+
    <input TYPE="submit" >

</form>

</body>
</html>

其在Servlet类中写入方法体

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobby = req.getParameterValues("hobby");(获取多个参数)

        System.out.println("username:"+username);
        System.out.println("密码"+password);
        System.out.println("兴趣爱好"+ Arrays.asList(hobby));
    }

解决post请求中文乱码
在doPost方法头部中写入
 //设置请求体字符集为UTF-8
        req.setCharacterEncoding("UTF-8");
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求体字符集为UTF-8
        req.setCharacterEncoding("UTF-8");
        
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] hobby = req.getParameterValues("hobby");

        System.out.println("username:"+username);
        System.out.println("密码"+password);
        System.out.println("兴趣爱好"+ Arrays.asList(hobby));

        System.out.println("POST");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值