1、Servlet目录结构
项目文件夹/WEB-INF/classes/.class文件
项目文件夹/WEB-INF/lib/所需要的jar包
项目文件夹/WEB-INF/web.xml配置文件
2、xml配置文件
< xml version=”1.0″ encoding=”ISO-8859-1″ >
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd”
version=”3.0″
metadata-complete=”true”>
Welcome to Tomcat
Welcome to Tomcat
//名字自己随便起
Hello
//对应的class文件 包名+类名
aa.Hello
//此与中的一定相同
Hello
//浏览器访问地址 随便写!
/sp
3、servlet编程 (实现Servlet接口方式)
package aa;
import javax.servlet.*;
import java.io.*;
public class Hello implements Servlet {
//销毁servlet实例(释放内存)
//1、reload 该servlet
//2、关闭tomcat
//3、关机
public void destroy() {
System.out.println(“destory!”);
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
//该函数用于初始化servlet(类似于构造函数)
//该函数只会被调用一次!
//当用户第一次访问该servlet时调用
public void init(ServletConfig arg0) throws ServletException {
System.out.println(“init it”);
}
//该函数用于处理业务逻辑
//程序员应该把业务逻辑代码写在这里
//该函数会被调用多次, 用户每访问一次就会被调用一次!
//req 用于获得客户端信息
//res 用来向客户端返回信息
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
//从res中得到PrintWriter
System.out.println(“service it”);
PrintWriter pw = res.getWriter();
pw.println(“hello world!!”);
}
}