request内置对象

来源:互联网 发布:美工行业现状 编辑:程序博客网 时间:2024/06/16 07:30

JSP之中,request对象的最主要作用就是服务器端接收客户端的请求参数。

.1.1 获取参数值

获取单个参数:其中最常用的一个方法就是request.getParameter(),但是此方法只能接收单个参数

获取多个参数:但是对于checkbox这类的表单元素,多个元素name一样,我们在后台获取请求参数使用request.getParameterValues()。

<form action="page2.jsp" method="get">

<input type="text" name="username" value="" />

爱好:

<input type="checkbox" name="habit" value="football"/> 足球

<input type="checkbox" name="habit" value="basketball"/> 篮球

<input type="checkbox" name="habit" value="pingpangball"/> 乒乓

<input type="checkbox" name="habit" value="golf"/> 高尔夫

<input type="submit" value="提交"/>

</form>

 

<%

request.setCharacterEncoding("UTF-8");

String[] habits = request.getParameterValues("habit");

if (null != habits) {

for (String habit : habits) {

out.println(habit+"/");

}

}

String username = request.getParameter("username");

String us = new String(username.getBytes(),"ISO8859-1");

out.println("<br/>" + us);

%>

 

如果前台没有传递相关参数值,则要进行非空的判断

在写代码的时候,要有一种对象是否可能为空的强烈意识

1.2处理字符乱码问题

request.setCharacterEncoding(“UTF-8”)

只要是用户直接进行页面访问,那么请求类型就一定是get请求。在表单上也可以使用get请求,但是get请求有个问题,他会将所有的请求参数附在请求路劲后面,所有一般只能传递有限的数据,过多的数据还是需要使用post请求完成,一般get请求只能传递4-5k的数据量。特别在form表单提交的时候,我们使用post请求居多。