第一个servlet程序

文章目录

在原有工程上建立模块


添加web框架



前端

应用结构

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第一个后端程序启动</title>
</head>
<body>
      <form action="/servlet01/demo" method="get">
<!--          后期打包的  项目名servlet01
 /demo   前往后端的路径
 任何一个前端发送至后端的链接,都要从项目名为   起点
 后期会学习自动获取项目名的知识
 在此之前,注意要人为手动写
-->
        <input type="text" name="username" >

        <input type="submit" value="提交">

      </form>
</body>
</html>

配置前后端映射关系

java 复制代码
<?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-name>aa</servlet-name>
        <servlet-class>com.yanyu.Demo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>aa</servlet-name>
        <url-pattern>/demo</url-pattern>
    </servlet-mapping>
</web-app>

添加外部依赖库





后端代码

直接继承 HttpServlet

基础好的学生,自行,ctrl + 鼠标 单击 对应的 接口 和类 去研究底层



java 复制代码
package com.yanyu;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author yanyu666_508200729@qq.com
 * @Date 2024/10/12 23:47
 * @description:
 */
public class Demo extends HttpServlet {
//    ctrl  + o  实现   doget方法

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        super.doGet(req, resp);  删除/注释掉
//        避免乱码
//        设置请求编码   数据流   浏览器   ------------------》服务器
        request.setCharacterEncoding("utf-8");
//        设置响应的编码和类型   (响应:   数据流  服务器   ---》  浏览器)
        response.setContentType("text/html;characters=UTF-8");
        PrintWriter out = response.getWriter();
//        out  输出到浏览器的对象
//        以上编码设置主要是针对  tomcat  10  之前,tomcat  10  之后,无需设置
//        tomcat  已经处理 编码问题
//        推荐:编码处理还是写下(你不清楚,你的代码会部署在tomcat  哪个版本)
//        获取前端数据
        String name = request.getParameter("username");
        System.out.println(name);//  输出到  服务器控制台
        out.print("输出到浏览器" + name);
        



    }
}

启动配置






记得 apply


相关推荐
爱敲代码的菜菜3 小时前
【项目】基于正倒排索引的Java文档搜索引擎
java·开发语言·前端·javascript·搜索引擎·servlet
清空mega2 天前
第7章:JavaBean、Servlet 与 MVC——从 JSP 页面开发走向规范项目
java·servlet·mvc
huohuopro2 天前
idea配置servlet项目
java·servlet·intellij-idea
沉默-_-2 天前
接收请求:HttpServletRequest的几种用法
前端·servlet·firefox
我真会写代码2 天前
手写tomcat框架
java·servlet·tomcat
TDengine (老段)3 天前
TDengine 视图功能使用
大数据·数据库·servlet·时序数据库·tdengine·涛思数据
沉默-_-4 天前
【Servlet】浏览器与服务器的交互
服务器·servlet·交互
༄天M宇ༀ4 天前
E10: e-builder 低代码构建平台接口管理(E9建模版)
java·前端·spring·servlet·reactjs
ren049185 天前
网络知识和Servlet重点
网络·servlet
凌冰_6 天前
IDEA2025 基于 Jakarta EE 开发 Servlet + Thymeleaf
java·servlet