IntelliJ IDEA 手动创建Servlet项目环境

创建项目

  1. File -> New -> Project…
  2. 选择 Java -> Java EE -> Next
  3. 勾选”Create project from template”,选择”Command Line App”
  4. Project name: test
  5. Project location: /www/java/test
  6. Base package: com.hk
  7. Finish

配置项目

  1. 快捷键:Ctrl+;
  2. “Libraries”添加tomecat里lib目录中的”servlet-api.jar”
  3. “Artifacts”添加”Web Application:Exploded”
  4. 修改”Name: test”
  5. 在”Output Layout”的root下新建”WEB-INF”
  6. 在”WEB-INF”下新建”classes”
  7. 将右边的”test compile output”拖到classes目录下
  8. 在”WEB-INF”下新建”lib”
  9. 将右边的”servlet-api”拖到lib目录下
  10. OK

修改代码

  1. extends HttpServlet
  2. Ctrl+N, Override Methods…,选择”doGet”或”doPost”等。

原com/hk/Main.java

package com.hk;

public class Main {

    public static void main(String[] args) {
	// write your code here
    }
}

修改后

package com.hk;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/fun")
public class Main extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("Hello world!");
    }

    public static void main(String[] args) {
	// write your code here
    }
}

修改tomecat配置

修改tomcat8/conf/server.xml,在Host节下添加

// reloadable="true" 不用重新部署
<Context path="/test" docBase="/www/java/test/out/artifacts/unnamed" reloadable="true" crossContext="true"/>

重启tomecat

停止:tomcat8/bin/shutdown.sh 启动:tomcat8/bin/startup.sh

编译代码

IDEA中”Build”->“Build Artifacts…”->“test”->“Build”

运行测试

浏览器:http://localhost:8080/test/fun 命令行:curl "http://localhost:8080/test/fun" 即可看到”Hello world!”

添加.war打包

  1. 快捷键:Ctrl+;
  2. “Libraries”添加tomecat里lib目录中的”servlet-api.jar”
  3. “Artifacts”添加”Web Application:Archive” -> “For test”
  4. 修改”Name: test_war”
  5. 点击下面的”Create Manifest…“,放在src目录中或其它目录
  6. IDEA中”Build”->“Build Artifacts…”->“test_war”->“Build”
  7. war包就在”/www/java/test/out/artifacts/test_war/test_war.war”,重命名即可

^_^