先看一下官方对ServletRequest的描述
public interface ServletRequest
Defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet’s service method.
A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest.
它的功能是将客户端的请求信息提供给servlet,servlet容器会创建一个ServletRequest对象,并会将其作为一个参数传给servlet的service方法。
ServletRequest对象是在用户发送一个请求时创建的,并在下一个请求到来时销毁,也就是说一个请求对应一个ServletRequest对象。
Map<String, String[]> getParameterMap();
String getParameter(String name);
Enumeration<String> getParameterNames();
String[] getParameterValues(String name);
这四个方法的作用主要是获得客户端发送过来的参数和对应的值,由于每个参数可能对应多个值,所以Map的key是个String,而value是个String数组。
在前端页面中编写一个form表单
<form action="/http/test" method="get">
<label for="username"> username:label>
<input type="text" name="username" id="username">
<label for="passwd"> password:label>
<input type="password" name="passwd" id="passwd">
hobby<br>
guitar<input type="checkbox" name="hobby" value="guitar"><br>
piano<input type="checkbox" name="hobby" value="piano"><br>
keyboard <input type="checkbox" name="hobby" value="keyboard"><br>
<button type="submit">提交button>
form>
无论是get还是post,它发送请求参数以及相关信息都会被封装到ServletRequest对象中,我们可以很方便的通过上面的接口拿到信息。
setAttribute(String, Object)
getAttribute(String)
removeAttribute(String)
这三个接口功能类似于ServletContext的,只不过这是在请求域中设置属性,它的生命周期是一次请求的过程。
public class A extends GenericServlet {
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
req.setAttribute("from_a", "aaaa");
req.getRequestDispatcher("/b").forward(req, res);
}
}
public class B extends GenericServlet{
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
PrintWriter writer = res.getWriter();
Object from_a = req.getAttribute("from_a");
writer.write(from_a.toString());
}
}
首先往A的请求域中添加一个字段,下面调用getRequestDispatcher可以获得一个服务派发者对象,这里是派发到/b对应的服务中,然后调用forward方法传入req,res,这样两个服务共享一个ServletRequest对象。这也是从一个服务跳转到另一个服务的方式。
String getRemoteAddr()
Returns the Internet Protocol (IP) of the remote end of the connection on which the request was received.
String getRemoteHost()
Returns the fully qualified name of the address returned by getRemoteAddr().
int getRemotePort()
ServletRequest还有一些其它的方法,比如获得客户端的地址,主机名和端口等