HttpServletRequest类中的getAttribute()和getParameter()方法有什么区别?


当前回答

getParameter -用于从客户端的HTML页面获取所需的信息

getAttribute——用于获取先前在另一个或相同的JSP或Servlet页面中设置的参数。

基本上,如果您正在从一个jsp/servlet转发或只是从一个jsp/servlet转到另一个jsp/servlet,那么除非您选择将它们放在一个对象中并使用set-属性存储在一个会话变量中,否则就无法获得所需的信息。

使用getAttribute,您可以检索Session变量。

其他回答

The difference between getAttribute and getParameter is that getParameter will return the value of a parameter that was submitted by an HTML form or that was included in a query string. getAttribute returns an object that you have set in the request, the only way you can use this is in conjunction with a RequestDispatcher. You use a RequestDispatcher to forward a request to another resource (JSP / Servlet). So before you forward the request you can set an attribute which will be available to the next resource.

重要的是要知道属性不是参数。

属性的返回类型是Object,而参数的返回类型是String。在调用getAttribute(字符串名称)方法时,请记住必须强制转换属性。

此外,没有servlet特定的属性,也没有会话参数。

这篇文章的目的是联系@Bozho的回复,作为对其他人有用的额外信息。

getparameter ():

<html>
<body>
<form name="testForm" method="post" action="testJSP.jsp">
<input type="text" name="testParam" value="ClientParam">
<input type="submit">
</form>
</body>
</html>

    <html>
    <body>
    <%
    String sValue = request.getParameter("testParam");
    %>
    <%= sValue %>
    </body>
    </html>

request.getParameter("testParam")将从名为"testParam"的输入框的发布形式中获取值,即"Client param"。然后它会把它打印出来,所以你应该在屏幕上看到“Client Param”。因此request.getParameter()将检索客户端已提交的值。您将在服务器端获得该值。

getattribute (): request.getAttribute(),这都是服务器端完成的。你将属性添加到请求中,并将请求提交给另一个资源,客户端不知道这一点。所以所有处理这个问题的代码通常都在servlet中。getAttribute总是返回对象。

另一种应该使用.getParameter()的情况是在jsp中转发参数:

<jsp:forward page="destination.jsp">
    <jsp:param name="userName" value="hamid"/>
</jsp:forward>

在destination.jsp中,你可以像这样访问userName:

request.getParameter("userName")

getAttribute()和getParameter()之间的基本区别是返回类型。

java.lang.Object getAttribute(java.lang.String name)
java.lang.String getParameter(java.lang.String name)