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成功運行。