ITEEDU

JSP/Servlet: request

request隐含对象会转换为javax.servlet.http.HttpServletRequest型态的对象,HttpServletRequest对象是有关于客户端所发出的请求之对象,只要是有关于客户端请求的信息,都可以藉由它来取得,例如请求标头、请求方法、请求参数、使用者IP等等信息。

对于每一个用户请求,容器都会为它产生一个HttpServletRequest对象,在Servlet的doService()或doGet()、 doPost()等方法中,只有HttpServletRequest对象被认定为执行绪安全的(Thread-safe)。

下面这个例子可以让您取得使用者所发出的请求参数:

requestDemo.jsp
<%@page contentType="text/html;charset=Big5" 
import="java.util.*"%> 
<html> 
<head><title>取得请求参数</title></head> 
<body> 
<h1>取得请求「参数=值」</h1> 
<% 
Enumeration params = request.getParameterNames(); 
while(params.hasMoreElements()) { 
String param = (String) params.nextElement(); 
out.println(param + " = " +
request.getParameter(param) + "<br>"); 
} 
%> 
</body> 
</html> 

getParameterNames()可以让您取得客户端所发出的请求参数名称,而getParameter()可以让您指定请求参数名称,以取得对应的设定值,如果这个JSP名称是requestdemo.jsp,而您在浏览器中键入:

http://localhost:8080/myjsp/requestDemo.jsp?name=justin&nick=caterpillar

也就是说您发出的请求「参数=值」为name=justin以及nick=caterpillar,则网页的执行结果是:

<html> 
<head><title>取得请求参数</title></head> 
<body> 
<h1>取得请求「参数=值」</h1> 
nick = caterpillar<br> 
name = justin<br> 
</body> 
</html> 

当然实际应用上,并不是要求用户直接在网址列上键入以上的参数,而是透过窗体来传送参数,如果窗体中的字段发送的是中文,则在取得请求参数之前,必须先指定发送过来的请求编码,例如若是Big5中文的话,则必须先执行以下这行:

request.setCharacterEncoding("Big5");

当然每一次都要先执行这行的话有些麻烦,建议可以将这行放在中。

与客户端发出的讯息相关的,我们都可以透过request(HttpServletRequest)对象来取得,例如下面的程序可以取得一些客户端的讯息:

requestDemo.jsp
<%@page contentType="text/html;charset=big5"
import="java.util.*"%> 
<html> 
<head><title>取得客户端信息</title></head> 
<body> 
<h1>取得客户端信息</h1> 
请求的服务器: <%= request.getServerName() %> <br> 
使用协议: <%= request.getProtocol() %> <br> 
请求方法: <%= request.getMethod() %> <br> 
请求的埠号: <%= request.getServerPort() %> <br> 
Context路径: <%= request.getContextPath() %> <br> 
Servlet路径: <%= request.getServletPath() %> <br> 
URI路径: <%= request.getRequestURI() %> <br> 
查询字符串: <%= request.getQueryString() %> <br>
<br> 
使用者主机IP: <%= request.getRemoteAddr() %> <br> 
使用者使用埠号: <%= request.getRemotePort() %> 
</body> 
</html> 

如果我们还是使用以下的请求方式:

http://localhost:8080/myjsp/requestDemo.jsp?name=justin&nick=caterpillar

则JSP网页会传回以下的讯息,以下直接显示网页上的文字:

取得客户端信息 

请求的服务器: localhost 

使用协议: HTTP/1.1

请求方法: GET 

请求的埠号: 8080

Context路径: /myjsp

Servlet路径: /requestdemo.jsp

URI路径: /myjsp/requestdemo.jsp 

查询字符串: name=justin&nick=caterpillar

使用者主机IP: 127.0.0.1

使用者使用埠号: 1060

关于更多request(HttpServletRequest)对象可用的方法,可以查询Servlet API Javadocs中有关于HttpServletRequest的部份(Tomcat安装后可以在安装目录中的webapps/tomcat- docs/servletapi/index.html 查询到)。