SERVLET是一种特殊的CGI
与CGI不同是多线程,性能很高
package cn.mldn.lxh.servlet ;
import java.io.* ;
// HttpServlet属于javax.servlet.http包下
// ServletException属于javax.servlet包下
import javax.servlet.* ;
// HttpServletRequest、HttpServletResponse存放在javax.servlet.http包下
import javax.servlet.http.* ;
public class SimpleServlet extends HttpServlet
{
// 表示处理get请求
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
{
PrintWriter out = resp.getWriter() ;
out.println("<HTML>") ;
out.println("<HEAD>") ;
out.println("<TITLE>THE FIRST SERVLET</TITLE>") ;
out.println("</HEAD>") ;
out.println("<BODY>") ;
out.println("<H1>Hello World!!!</H1>") ;
out.println("</BODY>") ;
out.println("</HTML>") ;
out.close() ;
}
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
{
this.doGet(request,response) ;
}
};
/**//*
<servlet>
<servlet-name>simple</servlet-name>
<servlet-class>cn.mldn.lxh.servlet.SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>simple</servlet-name>
<url-pattern>/demo</url-pattern>
</servlet-mapping>
*/
输出 Html用out.println()
很难维护
生命周期
生老病死(与人相似)
package cn.mldn.lxh.servlet ;
import java.io.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;
public class LifeCycleServlet extends HttpServlet
{
// 初始化
public void init(ServletConfig config) throws ServletException
{
System.out.println("** Servlet 初始化 ") ;
}
// 表示处理get请求
public void doGet(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
{
System.out.println("** Servlet doGet处理 ") ;
}
// 处理post请求
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException,ServletException
{
System.out.println("** Servlet doPost处理 ") ;
}
// 销毁
public void destroy()
{
System.out.println("** Servlet 销毁 ") ;
}
};
/**//*
<servlet>
<servlet-name>life</servlet-name>
<servlet-class>cn.mldn.lxh.servlet.LifeCycleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>life</servlet-name>
<url-pattern>/lc</url-pattern>
</servlet-mapping>
*/
init
doservices
destroy
创建要求
继承HttpServlet(先导入javax.servlet.*)必须在包中
在web-inf/class下
重写两个方法
doGet(req,resp)throws IOException(javax.servlet.http.*,java.io.*)
用PrintWriter输出
修改WEB.XML文件,映射SERVLET
<servlet>
<servlet-name>simple</servlet-name>
<servlet-class>cn.mldn.lxh.servlet.SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>simple</servlet-name>
<url-pattern>/demo</url-pattern>//在地址中输入的内容</servlet-mapping>
笔记下载
servlet只初始一次(在第一次使用servlet程序后,也可以在
容器启动时初始化servlet程序,通过修改web.xml文件)
<load-on-startup>1</load-on-startup>
doGet,doPost(doget是输入地址,doPost是表单请求)
destroy(服务器关闭,或者长时间不用)
注意
开发框架和配置