10.4 在Servlet中读取参数
1.任务1--在Servlet中读取参数
在Servlet中获取web.xml配置文件中设置的参数.
说明:和系统有关的配置信息,如:字符编码、数据库连接等信息一般放置在配置文件中,但自己写配置文件一般比较麻烦,可以将参数设置在web.xml配置文件中。
提示: <context-param> 用来设置全局参数; <init-param> 用来设置局部参数。
package test;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetParameter extends HttpServlet{
private static final long seralVersionUID=1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletContext application=this.getServletContext();
String encoding =application.getInitParameter("encoding");//利用application获取全局参数
System.out.println("encoding参数是:"+encoding);
String driverClassName=this.getInitParameter("driverClassName");//利用this获取当前Servlet的局部参数
System.out.println("driverClassName参数是:"+driverClassName);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<!-- 设置全局参数(所有的Servlet都可以访问):必须位于web.xml的最上面 -->
<!-- <context-param>用来设置全局参数 -->
<context-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</context-param>
<servlet>
<servlet-name>GetParameter</servlet-name>
<servlet-class>test.GetParameter</servlet-class>
<!-- 设置局部参数 -->
<init-param>
<param-name>driverClassName</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>GetParameter</servlet-name>
<url-pattern>/test/GetParameter</url-pattern>
</servlet-mapping>
</web-app>