一、前期准备
JDK11、Tomcat10、IDEA
二、操作步骤
1.打开IDEA->File->Project新建一个Java项目
下一步,随意命名
2.工程名右键->Add Framework Support…
选中Web Application,点击OK
3.展开web->WEB-INF,在WEB-INF下面新建两个文件夹classes,lib
4.按下Ctrl+Shift+Alt+S打开Project Structure
点击Modules->Paths,单选Use module compile output path,Output path改为classes路径
然后点击Dependencies,点击下面的+号,选择JARs or Directories,选择lib目录,选择Classes,点击OK
5.将tomcat/lib目录下的servlet-api.jar复制到创建的lib目录下
6.改一下index.jsp下的title和body,运行一下
7.在src里面新建一个java class,尝试写一个servlet:
这里也是与其他版本不同的地方,老版本都是import javax.servlet.xxxxx,这里是import jakarta.servlet.xxxxx,具体应该import的包,可以展开servlet-api.jar看到。
import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(name = "login") public class Login extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML>"); out.println("<HTML>"); out.println(" <HEAD><TITLE>login</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" this is login page"); out.print(this.getClass()); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML>"); out.println("<HTML>"); out.println(" <HEAD><TITLE>login</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" this is login page"); out.print(this.getClass()); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
8.修改web.xml文件,如下:
servlet-name可以随意命名上下一致就可以,servlet-class应该与类名相同,url-pattern是与java class中的@WebServlet(name=“xxxx”)的xxxx相同,这里的xxxx就是路径。
9.运行,在地址栏后面输入我们的url,就可以访问到动态资源了