Create a Java Web Application using Embedded Tomcat (如何使用Embedded 创建一个基于Tomcat的Web 应用))

IDEA 2022创建Maven Web项目:两种方式详解与Tomcat配置 在Java Web开发中,Maven作为项目构建和依赖管理的核心工具,通过其标准化的项目对象模型(POM)和生命周期管理,极大地简化了项目的构建、依赖解析和打包部署流程。其核心原理在于通过坐标机制统一管理jar包,并结合本地仓库、远程中央仓库及镜像仓库实现高效的依赖获取。这一技术价值在于为开发者提供了可复用的项目模板(Archetype)和标准化的目录结构,从而提升团队协作效率与项目可维护性。在实际应用场景中,无论是快速创建企业级Web应用还是微服务模块,Maven都是不可或缺的基础设施。本文聚焦于使用ID 阅读详情

Table of Contents

This tutorial will show you how to create a simple Java web application using embedded Tomcat.

Follow each step to build an app from scratch, or skip to the end get the source for this article.

Sample code for the embedded Tomcat demo is available on GitHub.

Prerequisites

  • Basic Java knowledge, including an installed version of the JVM and Maven.
  • Basic Git knowledge, including an installed version of Git.

Create your pom.xml

Create a folder to hold your app and create a file called pom.xml in the root of that folder with the following contents:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.heroku.sample</groupId>
  <artifactId>embeddedTomcatSample</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>embeddedTomcatSample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <tomcat.version>7.0.34</tomcat.version>
  </properties>
  <dependencies>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-core</artifactId>
        <version>${tomcat.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-logging-juli</artifactId>
        <version>${tomcat.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <version>${tomcat.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jasper</artifactId>
        <version>${tomcat.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jasper-el</artifactId>
        <version>${tomcat.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jsp-api</artifactId>
        <version>${tomcat.version}</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>embeddedTomcatSample</finalName>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>appassembler-maven-plugin</artifactId>
            <version>1.1.1</version>
            <configuration>
                <assembleDirectory>target</assembleDirectory>
                <programs>
                    <program>
                        <mainClass>launch.Main</mainClass>
                        <name>webapp</name>
                    </program>
                </programs>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>assemble</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
  </build>
</project>

This pom.xml defines the dependencies that you’ll need to run Tomcat in an embedded mode.

The last 3 entries are only required for applications that use JSP files. If you use this technique for an application that doesn’t use JSPs then you can just include the first 3 dependencies.

There is also a single plugin defined. The appassembler plugin generates a launch script that automatically sets up your classpath and calls your main method (created below) to launch your application.

Add a launcher class

Create a file called Main.java in your src/main/java/launch directory and put the following in it:

package launch;

import java.io.File;
import org.apache.catalina.startup.Tomcat;

public class Main {

    public static void main(String[] args) throws Exception {

        String webappDirLocation = "src/main/webapp/";
        Tomcat tomcat = new Tomcat();

        //The port that we should run on can be set into an environment variable
        //Look for that variable and default to 8080 if it isn't there.
        String webPort = System.getenv("PORT");
        if(webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }

        tomcat.setPort(Integer.valueOf(webPort));

        tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
        System.out.println("configuring app with basedir: " + new File("./" + webappDirLocation).getAbsolutePath());

        tomcat.start();
        tomcat.getServer().await();  
    }
}

Add a Servlet

Create a file called HelloServlet.java in the src/main/java/servlet directory and put the following into it:

package servlet;

import java.io.IOException;

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

@WebServlet(
        name = "MyServlet", 
        urlPatterns = {"/hello"}
    )
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ServletOutputStream out = resp.getOutputStream();
        out.write("hello heroku".getBytes());
        out.flush();
        out.close();
    }
    
}

This is simple Servlet that uses annotations to configure itself.

Add a JSP

Create a file called index.jsp in the src/main/webapp directory:

<html>
    <body>
        <h2>Hello Heroku!</h2>
    </body>
</html>

Run your application

To generate the start scripts simply run:

$ mvn package

And then simply run the script:

$ sh target/bin/webapp

That’s it. Your application should start up on port 8080. You can see the JSP at http://localhost:8080 and the servlet and http://localhost:8080/hello

Deploy your application to Heroku

Create a Procfile

You declare how you want your application executed in Procfile in the project root. Create this file with a single line:

web: sh target/bin/webapp

Learn more about procfile.

Optionally Choose a JDK

By default, OpenJDK 1.6 is installed with your app. However, you can choose to use a newer JDK by specifying java.runtime.version=1.7 in thesystem.properties file.

Here’s what a system.properties file looks like:

java.runtime.version=1.7

You can specify 1.6, 1.7, or 1.8 (1.8 is in beta) for Java 6, 7, or 8 (with lambdas), respectively.

Deploy to Heroku

Commit your changes to Git:

$ git init
$ git add .
$ git commit -m "Ready to deploy"

Create the app:

$ heroku create
Creating high-lightning-129... done, stack is cedar
http://high-lightning-129.herokuapp.com/ | git@heroku.com:high-lightning-129.git
Git remote heroku added

Deploy your code:

$ git push heroku master
Counting objects: 227, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (117/117), done.
Writing objects: 100% (227/227), 101.06 KiB, done.
Total 227 (delta 99), reused 220 (delta 98)

-----> Heroku receiving push
-----> Java app detected
-----> Installing Maven 3.0.3..... done
-----> Installing settings.xml..... done
-----> executing .maven/bin/mvn -B -Duser.home=/tmp/build_1jems2so86ck4 -s .m2/settings.xml -DskipTests=true clean install
       [INFO] Scanning for projects...
       [INFO]                                                                         
       [INFO] ------------------------------------------------------------------------
       [INFO] Building petclinic 0.1.0.BUILD-SNAPSHOT
       [INFO] ------------------------------------------------------------------------
       ...
       [INFO] ------------------------------------------------------------------------
       [INFO] BUILD SUCCESS
       [INFO] ------------------------------------------------------------------------
       [INFO] Total time: 36.612s
       [INFO] Finished at: Tue Aug 30 04:03:02 UTC 2011
       [INFO] Final Memory: 19M/287M
       [INFO] ------------------------------------------------------------------------
-----> Discovering process types
       Procfile declares types -> web
-----> Compiled slug size is 62.7MB
-----> Launching... done, v5
       http://pure-window-800.herokuapp.com deployed to Heroku

Congratulations! Your web app should now be up and running on Heroku. Open it in your browser with:

:::term  
$ heroku open

This will show your your JSP and then you can navigate to /hello to see your servlet.

Clone the source

If you want to skip the creation steps you can clone the finished sample:

$ git clone git@github.com:heroku/devcenter-embedded-tomcat.git

Feedback

If this article is incorrect or outdated, or omits critical information, please let us know. For all other issues, please see our support channels.

IDEA Java web项目搭建以及连接Mysql数据库 IDEA Java web项目搭建以及连接Mysql数据库一、准备:1.本机装好jdk,并配置好环境变量。(这里不再赘述) 2.下载安装tomcat,并配置环境变量。(这里用的是tomcat7.5) 3.下载mysql jdbc的驱动程序。(这里用的是mysql5.6) 4.建立数据库。(这里就简单建立一个用户信息表)CREATE TABLE user_info ( id INT PR 阅读详情

相关推荐

【TCAX相关】Python 官方手册下载页面(中文+英文)

Python 官方手册下载页面(中文+英文) 中文: https://docs.python.org/zh-cn/3.8/archives/ https://docs.python.org/zh-cn/3.6/archives/ 英文: https://www.python.org/doc/versions/ https://docs.python.org/3/archives/ https://www.python.org/ftp/python/doc/ ...

Seekladoom的博客 1012

在github上托管Maven存储库

I have a fork of a small open sourced library that I'm working on on github. 我有一个小型开源库的分支,我正在github

p15097962069的博客 6742

Arcgis 10.3 与 ArcGIS Engine 10.3 安装与破解

Arcgis 10.3 与 ArcGIS Engine 10.3 安装与破解

weixin_52127098的博客 4726

解决pom导入依赖无法下载的办法

手动添加jar到maven仓库中代码 打开cmd 以管理员身份运行 mvn install:install-file -Dfile=本地jar位置 -DgroupId=jar的groud坐标 -DartifactId=jar的artifactId坐标 -Dversion=jar的版本坐标 -Dpackaging=jar ...

white_xiaosheng的博客 6671

SAP ERPsim生产拓展实验报告

ERP课的实验和实践,也是SAP竞赛玩的东西,除了界面不华丽外很像游戏而且是团队型的pvp大乱斗

m0_67262022的博客 2020

Masta调用Geometry Modeller(Space Claim)进行根据三维模型快速建模设置方法

masta中调用ANSYS的space claim的设置方法

xifegnlie的博客 244

Maven简介

1.简介 Maven项目对象模型(POM)是一个项目管理工具软件,可以通过简短的信息描述来管理项目的构造,报告和文档。 除了具有构建程序的功能外,Maven还提供了高级项目管理工具。由于Maven的默认构建规则具有很高的可重用性,因此通常可以使用两到三行Maven构建脚本来构建简单的项目。由于Maven的面向项目的方法,许多ApacheJakarta项目在发布时都使用Maven,并且采用Maven的公司项目所占的比例持续增长。 一、简单的小问题? 解释之前,提1个小问题。 1.1、假如你正在Eclipse

Q1368089323的博客 3721

Android系统开发工程师面试指南与参考答案

本文整理了Android系统开发工程师面试常见问题与参考答案。核心内容涵盖:1)Framework层定制方法,如修改HAL和系统服务;2)ANR问题分析工具(systrace)与解决方案;3)性能优化实践,包括开机加速和功耗管理;4)四大组件工作机制与应用案例;5)Native崩溃调试技巧。文章强调通过AOSP源码研究、工具使用和项目案例准备来提升面试表现,重点考察应聘者的系统开发深度和实操能力。参考答案均基于实际开发经验,提供可量化的优化成果说明。

郑伟强dev的专栏 257

If you encounter a maven error on your pom file saying web.xml is missing

If you encounter a maven error on your pom file saying web.xml is missing if you encounter a maven error on your pom file saying web.xml is missing and is set to true, then it means it is expe

nobody 2539

【python基础】一文掌握 Jupyter Notebook 的使用(超级详细!)

是一个非营利组织,致力于为多种编程语言的交互式计算开发开源软件、开放标准和服务。Jupyter 于 2014 年由 Fernando Pérez 从IPython衍生出来,支持几十种编程语言的执行环境。Jupyter 项目主要开发并支持(.ipynb 文件格式)、JupyterHub和JupyterLab等交互式计算产品。

数据知道的博客 1万+

风电光伏功率预测竞赛精华总结:技术解析与实战经验

本文深度解析新能源功率预测竞赛的技术要点与实战经验。首先介绍了风电、光伏功率预测对电网调度优化、降低运营风险的重要性,以及多个竞赛的基本概况。在数据特征分析部分,详细探讨了气象预报数据和功率数据的特征,包括时间周期性、数据质量问题及处理方法。针对异常值检测、数据标准化和特征工程(如时间特征、统计聚合特征、风速风向特征和滞后特征)提供了具体的技术实现方案。文章为新能源功率预测提供了实用的技术指导,对相关竞赛和实际应用具有重要参考价值。

算法工程师 206

SpringBoot工程的pom报错问题解决

eclipse使用maven搭建SpringBoot工程,pom.xml 第一行报错问题解决办法 最近想要用eclipse搭建Springboot项目,但是遇到一个问题,使用maven创建springboot工程,pom.xml第一行总是报错,放在报错处也没有提示信息,而且项目可以正常运行,如下图: POM文件org.apache.maven.archiver.MavenArchiver.g...

Dyong_1992的博客 1967

GEE聚类分析:基于sentinel-2 影像进行 K-Means 聚类分析

这篇博客介绍了如何使用 Google Earth Engine (GEE) 进行 K-Means 聚类分析,以识别感兴趣区域(ROI)内的不同地表覆盖类型。文章详细说明了从定义用户参数、准备参考区域、加载和预处理 Sentinel-2 图像,到训练 K-Means 聚类器并对图像进行聚类的完整流程。代码示例展示了如何设置参数、采样像素数据、训练聚类器,并将结果可视化。最后,还提供了将聚类结果导出到 Google Drive 的选项。通过该教程,用户可以掌握在 GEE 平台上进行地理数据聚类分析的基本方法。

此星光明博客 263

Create a Java Web Application Using Embedded Tomca

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34198881的博客 123

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Creating a Simple Web Application Using a MySQL Database

This document describes how to create a simple web application that connects to a MySQL database server. It also covers some basic ideas and technologies in web development, such as

1501

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

intellij创建一个web应用

1.准备环境MAC OS X 10.10 tomcat8.0.27 java1.8 IntellJ 142.准备过程在使用IntelliJ创建web应用的时候,我们需要提前安装好tomcat和jdk.3.具体步骤1.创建一个web工程:File -> New -> Project,出现下面的界面,点击左上角的java,选择Web Application,如下图: 点击Next,去定项目

lanyizheng blog 679

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

Tomcat服务器搭建与Java Web应用部署实战指南

Java Web服务器是运行动态Java Web应用的核心容器,它基于Servlet、JSP等Java EE规范,负责处理HTTP请求、管理会话并执行业务逻辑。其工作原理是通过类加载器加载Web应用,并由连接器处理网络通信,引擎解析请求并分发给对应的Wrapper(Servlet)。这项技术为Java Web开发提供了标准化、可移植的运行时环境,极大提升了开发效率和应用的可维护性。在实际的工程实践中,Tomcat因其轻量、稳定和开源特性,成为学习、测试乃至生产环境的首选。通过合理的环境配置、安全加固和部署标

weixin_30321709的博客 428

Struts2教程一——How To Create A Struts 2 Web Application

<!-- .dp-highlighter {width:95%!important} --> <!-- .footer {padding-top:4px; color:#666} --> 本教程讲解Struts2的安装并建立一个简单的应用 Struts2易于使用,但需要以下J2EE技术,包括: JavaFi

RO_wsy的专栏 1500

Deploying a web application to Jetty

Deploying a web application to Jetty Deploying a web application to Jetty « EnavigoDeploying a web application to JettyThe Jetty web ...

85

IDEA整合Tomcat:实现Java Web开发热部署与高效调试

在Java Web开发中,应用服务器是承载Web应用运行的核心环境,而Tomcat作为轻量级、开源的Servlet容器,被广泛用于开发和部署Java Web应用。其工作原理是通过解析Servlet和JSP规范,处理HTTP请求并生成响应。将Tomcat与集成开发环境(IDE)整合,能够显著提升开发效率,实现编码、调试、部署的一体化流程。这种整合的技术价值在于支持热部署,允许开发者在修改代码后无需重启服务器即可看到更新效果,同时便于进行断点调试,快速定位业务逻辑问题。在实际应用场景中,无论是新手搭建本地开发环

weixin_34355559的博客 387

IDEA 2022创建Maven Web项目全攻略:从环境配置到Tomcat部署

Maven作为Java项目的主流构建工具,通过pom.xml文件统一管理依赖和构建生命周期,其核心价值在于实现项目依赖的自动化管理和标准化构建流程。在Java Web开发中,Maven与Servlet/JSP技术栈结合,能够高效地构建、打包和部署Web应用程序。本文聚焦于使用IntelliJ IDEA这一高效集成开发环境,详细解析通过Maven Archetype骨架和手动搭建两种主流方式创建Web项目的完整步骤。内容涵盖JDK与Maven环境配置、pom.xml依赖管理、项目结构解析以及Tomcat服务器

weixin_30920597的博客 320

struts2笔记1-How To Create A Struts 2 Web Application

工具:myeclipse10 + tomcat7 Create Struts 2 Web Application With Artifacts In WEB-INF lib and Use Ant To Build The Application Step 1 - Create A Basic Java Web Application (就是新建一个项目,尽量选择J2EE6.0) St...

164

tomcat加载时报The web application [/dmscs] created a ThreadLocal with key of type

严重: The web application [/dmscs] created a ThreadLocal with key of type [com.opensymphony.xwork2.inject.ContainerImpl$10] (value [com.opensymphony.xwork2.inject.ContainerImpl$10@55a106]) and a value o

sgp4205的专栏 1889

idea 导入jar java ee_IDEA------创建JavaWeb工程以及添加tomcat并引入第三方jar包

IDEA—创建JavaWeb工程以及添加tomcat并引入第三方jar包流程废话不多说,直接上步骤。【注意IDEA版本不同,在按钮的布局上可能有所不同,但按钮名,以及方法流程一致】1.Create New Project 2.在Java目录下选择Web Aplliction。注意下方有JavaWeb项目的版本,在JAVA EE8里面只有4.0版本,如果想使用其他版本比如2.5或者3.0,则修改Ja...

weixin_29029731的博客 1107

如何使用maven创建一个web项目

创建一个最简单的maven项目: mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.mycompany.app -DartifactId=my-app       maven  web项目: mvn archetype:generate -DarchetypeGro...

阿O、不拽 232

How To Create A Struts 2 Web Application

This tutorial walks through installing the framework and creating a simple application.While the Struts 2 framework is simple to use, creating non-trivial applications assumes a working knowledge of ma

405
上一篇: J2EE应用服务器 Geronimo
下一篇: Open Source Project Advice
努力突破
博客等级 码龄17年 36粉丝 113原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值