web.xml文件中Servlet中配置如下:
<servlet> <servlet-name>loginServlet</servlet-name> <servlet-class>com.qcc.study.servlet02.LoginServlet</servlet-class> <!-- 配置Servlet初始化参数 --> <init-param> <param-name>initParam</param-name> <param-value>qcc</param-value> </init-param> <!-- Web容器启动时就加载并实例化该Servlet --> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>loginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <!-- 配置ContextParam全局参数 --> <context-param> <param-name>contextParam</param-name> <param-value>admin</param-value> </context-param>
使用示例如下:
有login.jsp页面,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="login" method="post"> user:<input type="text" name="username" /><br/> password:<input type="password" name="password" /><br/> <input type="submit" value="Submit" /> </form> </body> </html>
当访问该jsp页面,并点击表单的提交按钮时,会将表单数据发送到login这个地址,这个login对应定义的serlvet的<url-mapping>的入口文件,请求被LoginServlet的doPost()方法处理,
LoginServlet的源码如下:
package com.qcc.study.servlet02; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取servlet初始化参数: String initParam = getServletConfig().getInitParameter("initParam"); System.out.println("initParam: ---->" + initParam); //获取全局初始化参数: String contextParam = getServletContext().getInitParameter("contextParam"); System.out.println("contextParam: ---->" + contextParam); //获取用户提交过来的数据: String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println("用户提交的数据:" + username + " , " + password); } }
二者的区别:
<init-parm>配置在<servlet>标签中,用来初始化当前的Servlet的,属于当前Servlet的配置,因此存放在servletConfig对象中;
通过getServletConfig().getInitParameter("initParam")的方式获取;
<context-param>直接配置在web.xml的<web-app>标签中,属于上下文参数,在整个web应用中都可以使用,它是全局的,因此存放在servletContext对象中(即application对象);
通过getServletContext().getInitParameter("contextParam")的方式获取;
打印结果:
initParam: ---->qcc contextParam: ---->admin 用户提交的数据:admin , 123