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

然后 我们运行项目

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

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

相关推荐
zhanghaha13145 小时前
Python语言基础:4_数据类型转换
java·前端·python
larance5 小时前
机器学习特征预处理之标准化/归一化
开发语言·python·机器学习
农村小镇哥6 小时前
C#中的字符串格式化
服务器·开发语言·c#
Devin~Y6 小时前
互联网大厂Java面试实战:Spring Boot、MyBatis、Redis、Kafka、JWT、Spring Cloud 与 AI 场景追问
java·spring boot·redis·spring cloud·kafka·mybatis·spring security
花生了什么事o6 小时前
DDD:领域驱动设计的初步认识
java·数据库
BGK1123586 小时前
基于qemu_v8+optee 4.00 平台构建 ca/ta
java·大数据·数据库
Android洋芋6 小时前
AI辅助C盘清理
c语言·开发语言·人工智能·ai辅助c盘清理
何中应7 小时前
Spring Boot整合Doris
java·数据库·spring boot
笨笨饿7 小时前
101_详解USB协议
java·jvm·数据结构
工业HMI实战笔记7 小时前
【无标题】
大数据·人工智能·ui·自动化·人机交互·交互