先把文档贴出来:
/**
*
* Returns the value of the named attribute as an <code>Object</code>,
* or <code>null</code> if no attribute of the given name exists.
*
* <p> Attributes can be set two ways. The servlet container may set
* attributes to make available custom information about a request.
* For example, for requests made using HTTPS, the attribute
* <code>javax.servlet.request.X509Certificate</code> can be used to
* retrieve information on the certificate of the client. Attributes
* can also be set programatically using
* {@link ServletRequest#setAttribute}. This allows information to be
* embedded into a request before a {@link RequestDispatcher} call.
*
* <p>Attribute names should follow the same conventions as package
* names. This specification reserves names matching <code>java.*</code>,
* <code>javax.*</code>, and <code>sun.*</code>.
*
* @param name a <code>String</code> specifying the name of
* the attribute
*
* @return an <code>Object</code> containing the value
* of the attribute, or <code>null</code> if
* the attribute does not exist
*
*/
public Object getAttribute(String name);
/**
* Returns the value of a request parameter as a <code>String</code>,
* or <code>null</code> if the parameter does not exist. Request parameters
* are extra information sent with the request. For HTTP servlets,
* parameters are contained in the query string or posted form data.
*
* <p>You should only use this method when you are sure the
* parameter has only one value. If the parameter might have
* more than one value, use {@link #getParameterValues}.
*
* <p>If you use this method with a multivalued
* parameter, the value returned is equal to the first value
* in the array returned by <code>getParameterValues</code>.
*
* <p>If the parameter data was sent in the request body, such as occurs
* with an HTTP POST request, then reading the body directly via {@link
* #getInputStream} or {@link #getReader} can interfere
* with the execution of this method.
*
* @param name a <code>String</code> specifying the
* name of the parameter
*
* @return a <code>String</code> representing the
* single value of the parameter
*
* @see #getParameterValues
*
*/
public String getParameter(String name);
从文档中可以了解到,getAttribute得到的值有两种方法进行设置:1、由servlet的container进行设置(container可以简单理解为运行serlvet的容器,比如Tomcat);2、程序中手动调用request.setAttribute()进行设置,这种方式适用于后台的servlet之间传递数据,比如调用 request.getRequestDispatcher(一个资源).forward(request,response)
,关键在于两个servlet中的request是同一个就能拿到值。返回值为Object。
而getParameter则是获取前台http请求中queryString 、post data、form表单数据的途径,返回一个字符串值。当然,有可能queryString和form表单中提交的数据key相同,值不同,所以ServletRequest接口中还提供了了一个 getParameterValues()
方法返回一个字符串数组。因为getParameter的作用就是获取用户前台填写的参数,所以规范中不允许程序私自设置parameter的值,因此ServletRequest接口中没有提供setParameter方法。
getAttribute和getParameter是两个互不相干的方法,取值的source各不相同,因此不会互相干扰。