getAttribute()与getParameter的区别

2019-12-10 20:02:15于海丽

当两个Web组件之间为转发关系时,转发源会将要共享 request范围内的数据先用setAttribute将数据放入到HttpServletRequest对象中,然后转发目标通过 getAttribute方法来取得要共享的数据。而MVC中用的就是Web组件之间的转发。 
下面整理一下getParameter和getAttribute的区别和各自的使用范围。

(1)HttpServletRequest类有setAttribute()方法,而没有setParameter()方法

(2)getParameter()用于用于客户端重定向时,即当两个Web组件之间为链接关系时,被链接的组件通过getParameter()方法来获得请求参数,例如假定welcome.jsp和authenticate.jsp之间为链接关系,welcome.jsp中有以下代码:

authenticate.jsp

或者:


请输入用户姓名:

在authenticate.jsp中通过request.getParameter("username")方法来获得请求参数username:

<% String username=request.getParameter("username"); %>