使用IntelliJ IDEA配置Tomcat和创建Servlet的步骤
1.新建WEB工程
2.在web/WEB-INF目录下新建两个文件夹,classes用于存放servlet的字节码文件(.class),lib用于存放项目引用的包。
3.按f4进入Project Structure,进入Modules(IDEA的工程)选项卡,将Paths的两个输出路径均改成第2步新建的classes。
4.然后点击Dependencies,选择右边+号,新建JARS路径,选择第2步创建的lib文件夹。
5.进入Artifacts选项卡,将输出目录定为Tomcat安装位置的webapps下新建的该工程文件夹
6.Run->Edit Configurations配置Tomcat,一般已经默认配好。
7.将WEB资源名定好,也可以是“/”,为空。
8.src下新建servlet
9.配置好web.xml,<servlet-class>指明servlet的编译出的字节码在哪个包下,<url-pattern>是servlet的资源名
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 5 version="3.1"> 6 <servlet> 7 <servlet-name>MyServlet</servlet-name> 8 <servlet-class>com.tqh.MyServlet</servlet-class> 9 </servlet> 10 <servlet-mapping> 11 <servlet-name>MyServlet</servlet-name> 12 <url-pattern>/A</url-pattern> 13 </servlet-mapping> 14 </web-app>
10.编写servlet
1 package com.tqh; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import java.io.IOException; 8 import java.io.PrintWriter; 9 10 public class MyServlet extends HttpServlet { 11 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 12 doGet(request,response); 13 } 14 15 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 16 response.setContentType("text/html"); 17 PrintWriter out=response.getWriter(); 18 out.println("this is servlet"); 19 } 20 }
11在IDEA运行Tomcat,打开浏览器按IP端口,资源名,<url-pattern>的顺序输入url,servlet成功运行。