1、写一个servlet类,继承httpservlet
public class HelloWorldServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); } public static void main(String args[]){ System.out.println("test"); } }
2、配置好tomcat的CATALINA_HOME为tomcat安装目录
3、把项目放在webapps文件夹下,项目文件夹下新建WEB-INF用于存放web.xml;WEB-INF中再新建classes文件件用于存放servlet类的.class文件。lib文件夹放需要使用的jar包
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" 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_2_5.xsd" version="2.5"> <servlet> <servlet-name>hw</servlet-name> <servlet-class>HelloWorldServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hw</servlet-name> <url-pattern>/abc</url-pattern> </servlet-mapping> </web-app>
servlet-name要与mapping中的servlet-name对应。url-pattern是访问这个servlet的相对路径。servlet-class必须是servlet类的名字。
如果servlet的类在包里面,比如com.yjh.HelloWorldServlet,则servlet-class也要写全com.yjh.HelloWorldServlet
4、读取GET、POST的参数
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- 包含三个输入框的表单 --> <HTML> <HEAD> <TITLE>Collecting Three Parameters</TITLE> </HEAD> <BODY BGCOLOR="#FDF5E6"> <H1 ALIGN="CENTER">Collecting Three Parameters</H1> <FORM ACTION="servlet/HelloWorldServlet" METHOD="GET"> First Paxxxrameter: <INPUT TYPE="TEXT" NAME="param1"><BR> Second Parxxxameter: <INPUT TYPE="TEXT" NAME="param2"><BR> Third Parametxxer: <INPUT TYPE="TEXT" NAME="param3"><BR> <CENTER><INPUT TYPE="SUBMIT"></CENTER> </FORM> </BODY> </HTML
<servlet-mapping> <servlet-name>hw</servlet-name> <url-pattern>/servlet/HelloWorldServlet</url-pattern> </servlet-mapping>
urlmapping的地址一定要跟HTML中action相对应。
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw=response.getWriter(); pw.println(request.getParameter("param1")); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); }
然后获得输出流,打印参数。