Servlet获取web.xml中的参数方法

 

 

  <context-param>
  <param-name>count</param-name>
  <param-value>1200</param-value>
  </context-param>

 

 

<servlet>
    <description>loginServlet</description>
    <display-name>loginServlet</display-name>
    <servlet-name>loginServlet</servlet-name>
    <servlet-class>loginServlet</servlet-class>
    <init-param>
      <description>系统初始化数</description>
      <param-name>num</param-name>
      <param-value>100</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>loginServlet</servlet-name>
    <url-pattern>/loginServlet</url-pattern>
  </servlet-mapping>

 

 

获取参数的方法以及异同

 

String username=request.getParameter("username");
  response.setCharacterEncoding("gb2312");
  System.out.println("getServletContext():"+getServletContext());
  ServletContext context=getServletConfig().getServletContext();
  String num=context.getInitParameter("num");// <init-param> 获取不到值
  String count=context.getInitParameter("count");//<context-param> 获取到值

  System.out.println("num:"+num);//null
  System.out.println("count:"+count);//1200
  System.out.println("num:"+getServletConfig().getInitParameter("num"));//100获取到值
  System.out.println("count:"+getServletConfig().getInitParameter("count"));//null获取不到值

  
  System.out.println("request.getSession().getServletContext():"+request.getSession().getServletContext());
  request.setAttribute("username", username);
  PrintWriter out=response.getWriter();
  out.println("获取的用户名是:"+username);

 

 

你可能感兴趣的:(Web,xml,servlet)