service方法:根据请求的方式调用doGet()或doPost():
public class Servlet1 extends HttpServlet {
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
System.out.println("do it");
super.service(arg0, arg1);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("do");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
读取配置信息(ServletConfig):
1.在web中配置初始化信息
servlet>
servlet-name>ConfigDemo</servlet-name
servlet-class>cn.java.ConfigDemo</servlet-class
init-param>
param-name>conf</param-name
param-value>lanhaoren</param-value
/init-param>
/servlet>
2.编写servlet程序
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//String info = this.getServletConfig().getInitParameter(“conf”);
//response.getWriter().print(info);
//同时取多个
Enumeration uu = this.getServletConfig().getInitParameterNames();
while(uu.hasMoreElements()){
String key = (String) uu.nextElement();
String value = getInitParameter(key);
response.getWriter().print(value);
注解的方式:
单个参数
@WebServlet(urlPatterns="/Servlet1",initParams = {@WebInitParam(name=“name”,value=“lanhaoren”)})
多个参数
@WebServlet(urlPatterns="/Servlet1",initParams = {@WebInitParam(name=“name”,value=“lanhaoren”),@WebInitParam(name=“gender”,value=“男”)})