Servlet系列之第一个web程序
创建第一个普通的web项目步骤[idea2022.1.4版]
1、打开idea开发工具,创建java web项目
文件 - > 新建 -> 项目
2、然后我们添加框架支持,因为新版IDEA需要我们手动导入Web框架
项目名称鼠标右击 - > 添加框架支持
3、进入项目结构
文件 - > 项目模块 -> 导出上方+ -> 选择库 -> 添加Tomcat[安装教程百度] -> 点击应用
4、点击Add Configration 部署Tomcat服务
点击修复后点击应用
5、新建如下图文件
代码如下
package com;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("first web project");
System.out.println("my first web project");
}
}
<?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_4_0.xsd"
version="4.0">
<!--配置servlet的别名,同时在servlet-class配置项中添加servlet类的完全限定名 包名+类名-->
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.MyServlet</servlet-class>
</servlet>
<!--配置servlet跟请求的映射关系-->
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
</web-app>
6、运行项目
出现下图代表部署Web项目成功
运行自己创建的地址 http://localhost:8080/JWebTest_war_exploded/first
注:/JWebTest_war_exploded是在编辑配置里配置的如下图
红框名字更改时访问地址也需要更改