我使用的编辑器是Intellj Idea,并且配置maven插件,无论是Intellj还是eclipse,重要的是编程思想,无所谓编辑器。
1. 编写一个Servlet实现类:HelloServlet:
import javax.servlet.*;importjava.io.IOException;public class HelloServlet implementsServlet {
@Overridepublic void init(ServletConfig servletConfig) throwsServletException {
System.out.println("int...");
}
@OverridepublicServletConfig getServletConfig() {
System.out.println("config...");return null;
}
@Overridepublic void service(ServletRequest servletRequest, ServletResponse servletResponse) throwsServletException, IOException {
System.out.println("service...");
}
@OverridepublicString getServletInfo() {
System.out.println("servletInfo...");return null;
}
@Overridepublic voiddestroy() {
System.out.println("destory...");
}
}
2.在web.xml文件中注册servlet实现类:
HelloServlet
com.yding.web.HelloServlet
HelloServlet
/hello
3.启动tomcat,将web项目部署到tomcat中,第一次访问http://localhost:8080/JavaWeb/hello时,servlet初始化,调用init()方法,并调用service方法,
在以后访问此链接时,都会调用service()方法,当服务器关闭时,会调用destroy()方法。
int...
service...
service...
destory...
4. 参数,可以控制servlet的加载时间,1表示加载tomcat同时加载servlet
HelloServlet
com.yding.web.HelloServlet
1
5.servlet可以匹配多个映射:
HelloServlet
/hello
HelloServlet
/hello2
6.serlet的URL通配符
通配符只可以有两种形式: 第一种形式: .action 或.html等 第二种形式:/* 不可以 /*.action
7.servletConfig,这是servlet的参数
HelloServlet
com.yding.web.HelloServlet
username
root
password
lfdy
1
public void init(ServletConfig servletConfig) throwsServletException {
String username= servletConfig.getInitParameter("username");
System.out.println(username);
String password= servletConfig.getInitParameter("password");
System.out.println(password);
System.out.println("int...");
Enumeration enumeration =servletConfig.getInitParameterNames();while(enumeration.hasMoreElements()){
String name=enumeration.nextElement();
String value=servletConfig.getInitParameter(name);
System.out.println(name+": "+value);
}
}
结果:
root
lfdyint...
password: lfdy
username: root