// 当用户第一次访问时调用
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("init....");
}
// 当用户访问时调用
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("service");
}
// 当服务器关闭时调用
public void destroy() {
System.out.println("destory");
}
如果追求更少的代码,只需要继承HttpServlet就行了,下面是简单实例
@WebServlet("/demo3")
public class ServletDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Get ...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Post ...");
}
}
request.setCharacterEncoding("UTF-8");