Web
首先在IDEA的社区版里File>>New>>Project创建一个普通的Java项目
然后在src同目录下创建一个Web目录,包含WEB-INF目录,接着在WEB-INF目录下创建classes目录,lib目录和web.xml文件,如下图所示
注意这里可以将servlet的jar包导入到lib目录下,也可以导入到External Libraries里
web.xml文件内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?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_3_1.xsd" version="3.1"> <servlet> <servlet-name>hello</servlet-name> <servlet-class>com.automne.HelloWorldController</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
|
HelloWorldController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.automne;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter;
public class HelloWorldController extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); out.write("hello!"); } }
|
然后就是配置servlet容器-Tomcat了
在社区版里,需要下载Smart Tomcat插件
安装重启IDEA后生效,接着Edit Configurations,尤其注意下图标记的地方
Deployment Directory里设置的必须是servlet项目里,WEB-INF目录的上层目录,在这里就是D:\Learning\IdeaProjects\ServletBase\Web
Context Path可以任意
运行上面的Tomcat后,访问发现正常解析了servlet
参考链接:
https://blog.csdn.net/hungrysoul/article/details/80916082