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作用域 那么 我们就将他输出在界面上就好了

然后 我们运行项目

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

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

相关推荐
白远山13 分钟前
上海24小时自助健身房解决方案实战指南与经验分享
java·数据库·架构·需求分析
码兄科技19 分钟前
24小时自助健身房系统软件开发实战指南:功能设计与部署方案
java·spring boot·uni-app
程序猿_极客24 分钟前
【免费】分享一套优质的基于SpringBoot的扶贫助农管理系统(详解)
java·springboot·课程设计·计算机项目
2603_9651481140 分钟前
AI+API选品:下一代智能商务助手雏形已现
java·大数据·数据库·人工智能·数据挖掘
wuminyu40 分钟前
HotSpot的轻量锁与膨胀后的ObjectMonitor状态重建原理
java·linux·c语言·jvm·c++
CoderYanger1 小时前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
北冥有鱼被烹1 小时前
perftest 之 ib_write_bw --use-null-mr 参数详解:用 NULL MR 做 RDMA 带宽测试
java
2601_963870211 小时前
基于SSM的特产代购系统
java·前端
牧瀬クリスだ1 小时前
YAML配置详解:SpringBoot实战指南
java·spring·yml