Servlet--Hello world

前提:JDK,Eclipse,Tomcat装好,环境变量配好

  1. 添加Eclipse的Tomcat插件(下载路径:http://www.eclipsetotale.com/tomcatPlugin.html
  2. 插件装好之后Window -〉 Perferences -〉 Tomcat 配置Tomcat路径,然后重启eclipse
  3. 新建一个Tomcat Project:ServletDemo
  4. 右键ServletDemo工程 -〉 创建一个Class:ServletDemo.java(创建的Class会自动生成到/WEB-INF/src目录中)(参考下文)
  5. 在WEB-INF下添加web.xml(参考下文)
  6. 点开Project看看Build Automatically又没有钩上,没有钩上说明不是自动编译,需要手动Alt + B编译一下
  7. 启动Tomcat,IE输入http://localhost:yourport/yourpath/show运行
//ServletDemo.java
import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
public class ServletDemo extends HttpServlet {  
  
    private static final long serialVersionUID = 382354197754278695L;  
  
    @Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {  
        resp.setContentType("text/html;charset=UTF-8");  
        PrintWriter out = resp.getWriter();  
        out.println("<html><head>");  
        out.println("<title>First Servlet Hello</title>");  
        out.println("</head><body>");  
        out.println("Hello!Servlet!");  
        out.println("</body></html>");  
        out.close();  
  
        super.doGet(req, resp);  
    }  
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  
    <servlet>  
        <servlet-name>Servlet</servlet-name>  
        <servlet-class>ServletDemo</servlet-class>  
        <load-on-startup>0</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>Servlet</servlet-name>  
        <url-pattern>/show</url-pattern>  
    </servlet-mapping>  
</web-app>

你可能感兴趣的:(java,servlet)