JSP编写自己的第一个WebServlet实现客户端与服务端交互

我们在项目中找到java目录 下面有一个包路径 然后 我们在下面创建一个类

我这里叫 TransmissionTest

当然 名字是顺便取的

参考代码如下

java 复制代码
package com.example.dom;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/1cginServlet")
public class TransmissionTest extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置客户端编码
        request.setCharacterEncoding("UTF-8");
        String userName = request.getParameter("userName");
        request.setAttribute("userName",userName);
        request.getRequestDispatcher("page.jsp").forward(request,response);
        return;
    }
}

这里 我们设置访问路径为 1cginServlet 这个名字也是自己取的

然后 继承 HttpServlet 规则

我们重写它的 service 函数

上来先将编码格式转成 UTF-8

然后 我们通过 getParameter 获取传过来的参数 userName 然后 将接收到的 userName 放入request作用域

最后 服务端跳转向 page.jsp

最后写完了 别忘了 return

然后 我们 index.jsp代码编写如下

html 复制代码
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%request.setCharacterEncoding("UTF-8");%>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Hello World</title>
</head>
<body>
    <form action="1cginServlet" method="post">
        用户名: <input type="text" name="userName"/>
        <button>提交</button>
    </form>
</body>
</html>

我们写了一个form表单 输入框用于输入用户名 我们定义的接受字段是 userName

然后 表单的提交格式是post 因为post保密性会强一些 然后 我们将数据提交到1cginServlet 就是我们刚刚类设置的路径 我们类中取到的userName字段 就是这个输入框中传递的

然后 我们创建一个page.jsp

编写代码如下

html 复制代码
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%request.setCharacterEncoding("UTF-8");%>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Hello World</title>
</head>
<body>
<%
    out.print("您输入的用户名是: "+ request.getAttribute("userName"));
%>
</body>
</html>

因为 我们类的逻辑是将userName 设入了 request作用域 那么 我们就将他输出在界面上就好了

然后 我们运行项目

例如 我们在 输入框中 顺便输入一个用户名 然后 我们点击提交

可以看到 展示也是没有任何问题

相关推荐
apcipot_rain4 小时前
C++转Java日记(06)
java·开发语言
金銀銅鐵8 小时前
带您看懂字节码指令(一):一帧里有什么
java·后端·ai编程
nice_lcj52010 小时前
【从零理解 Spring AI · 14】RAG 的四个环节:加载、切分、向量化、检索
java·spring boot·embedding·向量数据库·rag·spring ai·ai应用开发
SomeOtherTime10 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood11 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青11 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
学长毕设12 小时前
基于springboot科创竞赛信息平台-附源码
java·spring boot·后端
聪明的笨猪猪12 小时前
Java 工程案例:AI 生成 @Async 异步线程池踩坑
java·经验分享·面试·ai编程
学长毕设12 小时前
基于SpringBoot公务员考试交流平台-附源码
java·spring boot·后端
SL_staff15 小时前
私有化低代码:面向强监管行业的可控数字化实践
java·低代码