IDEA 创建Servlet-HelloWorldServlet

servlet

1.创建空项目

2.配置web项目



3.配置Tomcat




4.加载Tomcat包




5.创建HelloWorldServlet类

java 复制代码
public class controller extends HttpServlet {
    @Override
    //get请求
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	//页面显示servlet
        resp.getWriter().println("servlet");
    }

    @Override
    //post请求
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

6.配置web.xml

xml 复制代码
<?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>
<!--        java类路径别名-->
        <servlet-name>hello</servlet-name>
<!--        引入java类-->
        <servlet-class>com.lx.controller</servlet-class>
    </servlet>
    <servlet-mapping>
<!--        使用别名-->
        <servlet-name>hello</servlet-name>
<!--        浏览器资源路径-->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

7.运行


get与post请求

html 复制代码
<!--  /servletWebDemo:是配置Tomcat中指定的地址-->
<!--  /login:是web.xml中的<url-pattern>/login</url-pattern>-->
  <form action="/servletWebDemo/login" method="get">
    <label>用户名:</label>
    <input type="text" name="userName">
    <br>
    <br>
    <label>密码:</label>
    <input type="password" name="passWord">
    <br>
    <br>
    <button type="submit">提交</button>
  </form>
java 复制代码
public class controller extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置请求中文字符
        req.setCharacterEncoding("utf-8");
        //设置响应中文字符
        resp.setContentType("text/html;charset=utf-8");
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("passWord");
        resp.getWriter().println(userName);
        resp.getWriter().println();
        resp.getWriter().println(passWord);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
相关推荐
leikooo6 小时前
用餐厅和盘子理解栈和堆
java·数据结构·链表·rust
Ivanqhz7 小时前
激活函数在 Transformer 中的作用及各种变体简述
java·linux·数据库·人工智能·深度学习
沙漠之主7 小时前
C++编程教学设计资料:从入门到实战的完整课程方案
java·前端·c++
FPGA小徐7 小时前
PA1 基础设施(2)深度解析:NEMU 中 ITRACE、MTRACE、FTRACE、IRINGBUF、ETRACE、DIFFTEST 全解析
java·服务器·网络
YOLO数据集集合8 小时前
EvoAgent:面向PR研发治理的自进化Multi-Agent Harness系统
java·开发语言·目标检测·agent·自进化
知行EDI8 小时前
知行之桥 MaBang 端口使用指南——Create Order 订单创建篇
java·服务器·数据库
笑鸿的学习笔记8 小时前
C++笔记之大块顺序写
java·c++·笔记
打工仔折腾 AI8 小时前
从 Demo 到生产级 Agent:8 个关键设计机制与 Python 实现拆解
java·jvm·人工智能·后端·python·langchain·ai agent 实战
殷色玫瑰9 小时前
C/C++ 内存管理详解:从内存分布到 new/delete 底层原理
java·linux·c语言·c++
青山木11 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划