初學servlet之@WebServlet傳參
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 = " [email protected]")
})
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();
}
}
初學servlet之@WebServlet傳參