tomcat

@WebServlet

  • @WebServlet 是servlet 3.0的写法
  • 新建maven项目,结构如下

clipboard.png

  • pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.adagio</groupId>
  <artifactId>tomcat-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  
  <dependencies>
      <dependency>
         <groupId>Javax.servlet</groupId>
         <artifactId>javax.servlet-api</artifactId>
         <version>3.1.0</version>
         <scope>provided</scope>
     </dependency>

     <dependency>
         <groupId>org.apache.tomcat.maven</groupId>
         <artifactId>tomcat7-maven-plugin</artifactId>
         <version>2.1</version>
     </dependency>
  </dependencies>
  
  <build>
      <plugins>
          <plugin>
               <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>2.3.2</version>
              <configuration>
                  <source>1.8</source>
                  <target>1.8</target>
              </configuration>
          </plugin>
      
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-war-plugin</artifactId>
             <version>3.2.0</version>
             <configuration>
                 <failOnMissingWebXml>false</failOnMissingWebXml>
             </configuration>
          </plugin>
      </plugins>
  </build>
</project>
  • Java Code
package com.adagio;

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/demo")
public class DemoServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        String message = request.getParameter("message");
        
        response.getWriter().print(message);
        response.getWriter().println("<br/>");
        
    }
    
}
  • 打包:mvn -Dmaven.test.skip -U clean package
  • 启动:war包放到tomcat/webapps目录下,启动tomcat
  • 访问:http://localhost:8080/tomcat-demo-0.0.1-SNAPSHOT/demo?message=hello

使用maven插件,构建嵌入式容器

  • POM文件中添加
<plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <executions>
                    <execution>
                        <id>tomcat-run</id>
                        <goals>
                            <goal>exec-war-only</goal>
                        </goals>
                        <phase>package</phase>
                        <configuration>
                            <!-- ServletContext path -->
                            <path>/</path>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
  • 打包:mvn -Dmaven.test.skip -U clean package
  • 启动:java -jar targettomcat-demo-0.0.1-SNAPSHOT-war-exec.jar
  • 访问:http://localhost:8080/demo?message=hello
  • 解压jar包,找到 META-INF/MANIFEST.MF
Manifest-Version: 1.0
Main-Class: org.apache.tomcat.maven.runner.Tomcat7RunnerCli
  • 可以得出jar 的启动类:org.apache.tomcat.maven.runner.Tomcat7RunnerCli

模拟server.xml,构建嵌入式容器

源码


import java.io.File;

import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.Service;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

/**
 * 访问 : http://localhost:9527/index.jsp
 * http://localhost:9527/demo?message=hello
 *
 */
public class EmbeddedTomcatServer {

    public static void main(String[] args) throws Exception {
        
        //确定classes 目录绝对路径
        String calssesPath = System.getProperty("user.dir") + 
                File.separator + "target" + File.separator + "classes";
        System.out.println(calssesPath);
        
        //创建Tomcat实例
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(9527);
        
        //设置Host
        Host host = tomcat.getHost();
        host.setName("localhost");
        host.setAppBase("webapps");
        
        //设置 Context
        //server.xml - <Context docBase="" path="/" /></Host>
        String webapp = System.getProperty("user.dir") + File.separator
                + "src" + File.separator + "main" + File.separator + "webapp";
        String contextPath = "/";
        //设置 webapp 绝对路径到 Context,作为它的docBase
        Context context = tomcat.addWebapp(contextPath, webapp);
        if(context instanceof StandardContext) {
            StandardContext standardContext = new StandardContext();
            // 设置默认的web.xml文件到Context
            standardContext.setDefaultContextXml(calssesPath + File.separator + "conf/web.xml");
            
            //设置 Classpath 到Context
            // 添加DemoServlet到tomcat 容器
            Wrapper wrapper = tomcat.addServlet(contextPath, "DemoServlet", new DemoServlet());
            wrapper.addMapping("/demo");
        }
        
        
        //http://localhost:9526/demo?message=%E5%B0%8F%E9%A9%AC
        
        //设置Service
        Service service = tomcat.getService();
        Connector connector = new Connector();
        //这里设置了一个port,等于两个端口都可以使用,但是上面那个端口访问中文乱码
        connector.setPort(9526);
        connector.setURIEncoding("UTF-8");
        connector.setProtocol("HTTP/1.1");
        service.addConnector(connector);
        
        
        
        //启动 tomcat 服务器
        tomcat.start();        
        // 强制 Tomcat Server 等待,避免main线程执行结束关闭
        tomcat.getServer().await();
    }
}

文件

  • 直接从tomcat/conf copy web.xml到项目中
  • 在resources下建 conf目录,把copy的web.xml放进去
  • 在webapp下新建 index.jsp
  • 具体如图

... 未完


麦冬
315 声望13 粉丝

越成熟的稻穗,越饱满厚实