比较getAttribute()、getParameter()和getInitParameter()

来源:互联网 发布:警察如何查淘宝记录 编辑:程序博客网 时间:2024/06/06 17:12

下列方法的区别 

ServletRequest

      |--getAttribute():返回String。返回这个请求的身份验证模式(API是这样写)。可以得到由setAttribute()设置的参数值。在ServletContext域可以实现servlet之间的数据共享。

      |--getParameter(String name):返回String指定name的值。一般是客户端提交表单的信息中

ServletConfig

      |--getInitParameter(String name) :返回String可以得到指定web.xml文件中初始化参数信息。如:返回的值是“123”

  <servlet>      ..........  <init-param>    <param-name>data</param-name>    <param-value>123</param-value>    </init-param>  </servlet>

通过写代码和调试,明白了ServletRequest和ServletContext中的setAttribute()是不同的,即作用范围不同

package com.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Demo2 extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//客户端请求信息(封装成HttpServletRequest);String user=request.getParameter("user");String str="aaa";String str2="bbb";this.getServletContext().setAttribute("name", str);                 request.setAttribute("name2",str2);PrintWriter out=response.getWriter();out.println("------------request.getParameter('user'):"+request.getParameter("user"));out.println("------------request.getAttribute()      :"+request.getAttribute("name2"));out.println("getServletContext().getAttrubute()      :"+getServletContext().getAttribute("name"));/*输出结果如下: *------------request.getParameter('user'):admin------------request.getAttribute()      :bbbgetServletContext().getAttrubute()      :aaa * *若如上输出代码中name和name2换过来,结果会是null; *如此说明:request和ServletContext中的setAttribute()是不同的 *request域:是请求范围 *Servlet域:是该应用Servlet容器范围(故Servlet容器中的不同servlet可以通过setAttribute()和getAttribute()实现数据共享)     */}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request,response);}}
如有不符合的地方,请大家帮我指正。

	
				
		
原创粉丝点击