内部原理主要一个connector,一个container;connector主要负责解析网络请求,container负责生成一个ruquest和一个response;html
Servlet是sun公司提供的一门用于开发动态web资源的技术。
Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向浏览器输出数据),须要完成如下2个步骤:
一、编写一个Java类,实现servlet接口。
二、把开发好的Java类部署到web服务器中。
按照一种约定俗成的称呼习惯,一般咱们也把实现了servlet接口的java程序,称之为Servletjava
1:新建一个webproject,在src下新建一个package,在package下新建一个servlet类。以下:web
FirstServlet有以下代码:浏览器
package com.chengguruchun.study;服务器
import java.io.IOException;网络
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;app
public class FirstServlet extends HttpServlet {post
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {this
response.setContentType("text/html");spa
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
这些代码都是Eclipse自动生成的,而web.xml文件中也多了<servlet></servlet> 和<servlet-mapping></servlet-mapping>两对标签,这两对标签是配置First Servlet的,以下图所示:
第二步:在FirstServlet doget方法中写入以下代码:(引入相应的包import java.io.IOException;
import java.io.PrintWriter;)
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
第三步:咱们就能够经过浏览器访问FirstServlet这个Servlet,以下图所示:
ok了。