package app01a;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//传入两个初始参数
@WebServlet(name = "ServletConfigDemoServlet",
urlPatterns = { "/servletConfigDemo" },
initParams = {
@WebInitParam( name = "admin", value = " Harry Taciak"),
@WebInitParam( name = "email", value = " admin@example.com")
})
public class ServletConfigDemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private transient ServletConfig servletConfig;
/**
* 返回servletConfig
*/
@Override
public ServletConfig getServletConfig() {
return servletConfig;
}
/**
* 首先执行,在一次访问中从始至终只执行一次
*/
@Override
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig = servletConfig;
}
/**
* 第二执行,每次请求时都要执行
*/
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletConfig servletConfig = getServletConfig();
String admin = servletConfig.getInitParameter("admin");
String email = servletConfig.getInitParameter("email");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.print("<html><head></head><body>" + "Admin:" + admin + "<br/>Email:" + email +
"</body></html>");
}
/**
* 返回Servlet描述
*/
@Override
public String getServletInfo() {
return "ServletConfig demo";
}
/**
* 摧毁时调用
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
}
}