使用IDEA创建Java Web

Java Web实现

1.去官网下载好Tomcat,打开IDEA,新建Project,选择左侧的Java Enterprise,在Application Server处选择Tomcat和安装目录;勾选Web ApplicationCreate web.xml

点击Next,填写项目名称

2.在web/WEB-INF目录新建两个文件夹:classeslib

3.点击File->Project Structure

选择左侧Modules,切换到Paths选项,选择Use module compile output path,然后将下面两个path都选择创建的classes目录

4.切换到Dependencies选项,点击左下角+,选择JARs or directories,选择创建的lib目录;接着选择Jar Directory

5.点击左侧的Artifacts,勾选Include in project build,表示编译的时候就打包部署;勾选Show content of elements,表示显示详细的内容列表

做完上面几步后,点击右下角Apply,再点击OK

6.点击Run->Edit Configurations,去掉勾选After launch,然后配置HTTP portJMX port,点击右下角ApplyOK

7.运行,访问http://localhost:14330/javaweb_war_exploded/

Servlet实现

src目录创建HelloWorld.java文件,写入:

1
2
3
4
5
6
7
8
9
10
import java.io.*;
import javax.servlet.*;

public class HelloWorld extends GenericServlet {
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}

然后点击编译,它会自动在classes目录生成编译后的class文件:

然后编辑web.xml,在web-app标签内写入:

1
2
3
4
5
6
7
8
9
10
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>
HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/gtfly</url-pattern>
</servlet-mapping>

最后点击运行,访问/gtfly目录查看运行结果