详解如何使用IntelliJ IDEA新建一个Servlet项目

时间:2022-09-24 10:29:35

本文介绍了使用intellij idea新建一个servlet项目,一步步很详细,有需要的朋友可以了解一下

创建项目

详解如何使用IntelliJ IDEA新建一个Servlet项目

详解如何使用IntelliJ IDEA新建一个Servlet项目

创建完后的目录结构为:

详解如何使用IntelliJ IDEA新建一个Servlet项目

web项目配置

在web-inf目录下新建两个文件夹,分别命名未classes和lib(classes目录用于存放编译后的class文件,lib用于存放依赖的jar包)

详解如何使用IntelliJ IDEA新建一个Servlet项目

项目设置:file –> project structure…,进入 project structure窗口,点击 modules –> 选中项目“javaweb” –> 切换到 paths 选项卡 –> 勾选 “use module compile output path”,将 “output path” 和 “test output path” 都改为之前创建的classes目录

详解如何使用IntelliJ IDEA新建一个Servlet项目

点击 modules –> 选中项目“javaweb” –> 切换到 dependencies 选项卡 –> 点击右边的“+”,选择 “library…”,选择tomcat的库

详解如何使用IntelliJ IDEA新建一个Servlet项目

详解如何使用IntelliJ IDEA新建一个Servlet项目

详解如何使用IntelliJ IDEA新建一个Servlet项目

详解如何使用IntelliJ IDEA新建一个Servlet项目

编写servlet程序

在src目录下创建servlet文件:起名为testdemo,自动生成的接口没有@override需要自己加上,并且在doget接口中添加内容

详解如何使用IntelliJ IDEA新建一个Servlet项目

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@webservlet(name = "testdemo")
public class testdemo extends httpservlet {
  @override
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
 
  }
 
  @override
  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    response.setcontenttype("text/html");
 
    printwriter out = response.getwriter();
    out.println("<h1>hello world</h1>");
  }
}

修改web.xml文件内容:在webapp标签内部加上以下内容:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
     xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
     version="4.0">
  <servlet>
    <servlet-name>test</servlet-name>
    <servlet-class>testdemo</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>test</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

运行程序

配置tomcat容器:

详解如何使用IntelliJ IDEA新建一个Servlet项目

详解如何使用IntelliJ IDEA新建一个Servlet项目

配置好后运行程序,然后访问:http://localhost:8080/test

得到结果

详解如何使用IntelliJ IDEA新建一个Servlet项目

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/grasp/p/10023875.html