打包Servlet部署到Tomcat

2,253 阅读1分钟

编写Servlet

@WebServlet(name = "MyServlet", urlPatterns = { "/my"})
public class MyServlet implements Servlet {

  private transient ServletConfig servletConfig;

  public void init(ServletConfig config) {
    this.servletConfig = config;
  }

  public ServletConfig getServletConfig() {
    return servletConfig;
  }

  public void service(ServletRequest req, ServletResponse res) throws IOException {
    String name = getServletInfo();
    res.setContentType("text/html");
    res.setCharacterEncoding("UTF-8");
    PrintWriter pw = res.getWriter();
    pw.print("<html><head></head>" + "<body>欢迎来到" + name + "</body>" + "</html>");
  }

  public String getServletInfo() {
    return "My Servlet";
  }

  public void destroy() {

  }
}

部署描述符(src/main/webapp/WEB-INF/web.xml)

部署描述符总是命名为web.xml,并放在WEB-INF目录下

<?xml version="1.0"?>
<web-app
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">

    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>app01a.MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/my</url-pattern>
    </servlet-mapping>

</web-app>

把Servlet程序部署到Tomcat中

部署方式有两种:

  • 将应用程序的目录复制到Tomcat安装目录的webapps目录中,适合开发部署
  • 将应用程序打包成war包,同样放到webapps目录中,适合生产部署

开发部署

pom.xml配置如下

执行mvn命令

mvn clean compile war:exploded

生成如下目录文件

将目录添加到Tomcat的webapps中

启动Tomcat后访问

my:是servlet的映射url

生产部署

pom.xml

执行mvn命令

mvn clean package
或
mvn compile war:war

生成war包

部署war包到Tomcat

访问